Newer
Older
XinYang_IOS / XYSW / ViewController.m
@zhangfeng zhangfeng on 7 Dec 18 KB 1.8.0
//
//  ViewController.m
//  XYSW
//
//  Created by Jim on 2021/9/7.
//

#import "ViewController.h"

#import "YHScanQRCodeVC.h"
#import "TZImagePickerManager.h"
#import "WeDocument.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "LCDownloadManager.h"
#import <QuickLook/QuickLook.h>
#import <WebKit/WebKit.h>

#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<UIDocumentPickerDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate,CLLocationManagerDelegate>

@property (nonatomic , strong) UIImageView *pickerImageV;

@property (nonatomic, strong) AFHTTPRequestOperation *operation;

@property (nonatomic, strong) NSString *fileSvPath;

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation ViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setTitle:@"扫一扫" forState:UIControlStateNormal];
    [scanBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn.frame = CGRectMake(150, KNavHeight+40, 80, 25);
    scanBtn.backgroundColor = [UIColor blueColor];
    [scanBtn addTarget:self action:@selector(goToScanVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    
    _pickerImageV = [[UIImageView alloc] init];
    [self.view addSubview:_pickerImageV];
    [_pickerImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-34);
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(150);
        make.width.mas_equalTo(KScreenWidth);
    }];
    
    UIButton *scanBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    scanBtn1.backgroundColor = [UIColor blueColor];
    [scanBtn1 setTitle:@"拍照" forState:UIControlStateNormal];
    [scanBtn1 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn1.frame = CGRectMake(20, KNavHeight+40, 80, 25);
    [scanBtn1 addTarget:self action:@selector(goToCameraComplain) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn1];
    
    UIButton *scanBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn2 setTitle:@"相册" forState:UIControlStateNormal];
    scanBtn2.backgroundColor = [UIColor blueColor];
    [scanBtn2 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn2.frame = CGRectMake(260, KNavHeight+40, 80, 25);
    [scanBtn2 addTarget:self action:@selector(goToPickerImageComplain) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn2];
    
    UIButton *scanBtn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn3 setTitle:@"文件上传" forState:UIControlStateNormal];
    scanBtn3.backgroundColor = [UIColor blueColor];
    [scanBtn3 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn3.frame = CGRectMake(150, KNavHeight+100, 80, 25);
    [scanBtn3 addTarget:self action:@selector(goToopenFileData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn3];
    
    UIButton *scanBtn4 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn4 setTitle:@"退出登录" forState:UIControlStateNormal];
    scanBtn4.backgroundColor = [UIColor blueColor];
    [scanBtn4 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn4.frame = CGRectMake(150, KNavHeight+140, 80, 25);
    [scanBtn4 addTarget:self action:@selector(goToLoginViewControll) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn4];
    
    UIButton *scanBtn5 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn5 setTitle:@"文件下载" forState:UIControlStateNormal];
    scanBtn5.backgroundColor = [UIColor blueColor];
    [scanBtn5 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn5.frame = CGRectMake(150, KNavHeight+180, 80, 25);
    [scanBtn5 addTarget:self action:@selector(goToDownFile) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn5];
    
    
    UIButton *scanBtn6 = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn6 setTitle:@"获取定位" forState:UIControlStateNormal];
    scanBtn6.backgroundColor = [UIColor blueColor];
    [scanBtn6 setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    scanBtn6.frame = CGRectMake(150, KNavHeight+220, 80, 25);
    [scanBtn6 addTarget:self action:@selector(getLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn6];
}


-(void)getLocation{
   
    [self startLocation];
}


-(BOOL)getLocatoinAuth
{
    BOOL isAuthNotDeteermined = [CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined;
    BOOL isAuthNo = [CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied || [CLLocationManager authorizationStatus]==kCLAuthorizationStatusRestricted;
    if ([CLLocationManager locationServicesEnabled] && isAuthNotDeteermined)
    {
        CLLocationManager *locationManager = [[CLLocationManager alloc] init];
        [locationManager requestAlwaysAuthorization];
        
        return NO;
    }
    else if ([CLLocationManager locationServicesEnabled] && isAuthNo)
    {
        NSString *title=[NSString stringWithFormat:@"您尚未允许定位服务!\n请到手机[设置]->[隐私]->[定位服务]中打开定位服务,并允许香信使用定位服务。"];
        
       
        UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title
                                                                           message:nil
                                                                    preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure_simple",@"确定") style:UIAlertActionStyleCancel handler:nil];
        [alertCtrl addAction:cancelAction];
        
        [self presentViewController:alertCtrl animated:YES completion:nil];
        return NO;
    }
    return YES;
}
//开始定位
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        //控制定位精度,越高耗电量越
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 总是授权
        [self.locationManager requestAlwaysAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations[0];
    NSString *lat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
    NSString *lon = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
    NSString *alerStr = [NSString stringWithFormat:@"你好,你的经纬度信息为 : 纬度:%@  经度:%@",lat,lon];
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"提示" message:alerStr preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [actionSheet addAction:cancleAction];
    [self presentViewController:actionSheet animated:YES completion:nil];
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                city = placemark.administrativeArea;
            }
            NSLog(@"city = %@", city);
            
//            [self httpGetWeather:city];
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
}



-(void)goToDownFile{
    
    [self.view makeToast:@"没有文件路径"];
    
    //NSString *fileUrl=[body.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 下载路径
    NSString *fileUrl = @"";
    // 缓存路径
    long timeStamp = (long)([[NSDate date] timeIntervalSince1970]*1000);
    NSString* fileCachePath=[NSString stringWithFormat:@"%ld%@",timeStamp,@"fileName"];
    // 本地路径
    NSString *cacgeFileUrl = [NSString stringWithFormat:@"/%@/file/%@",@"kUid",fileCachePath];
    
    __weak typeof(self) weakSelf = self;
    
    [self.operation cancel];
    
    self.operation = [LCDownloadManager downloadFileWithURLString:fileUrl fileName:@"fileNamefileCachePath" cachePath: fileCachePath progress:^(CGFloat progress, CGFloat totalMBRead, CGFloat totalMBExpectedToRead) {
        // 正在下载
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        // 下载成功
        
        // 打开文件 预览
        NSString* fileUrl=[NSString stringWithFormat:@"%@%@",[[self class] XH_getDocumentDir],cacgeFileUrl];
        if (fileUrl) {
            weakSelf.fileSvPath = fileUrl;
            QLPreviewController *preViewCon = [QLPreviewController new];
             preViewCon.dataSource = weakSelf;
            [preViewCon setDelegate:weakSelf];
            [weakSelf presentViewController:preViewCon animated:YES completion:nil];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        //下载失败
        
    }];
    
    
    
}

-(void)goToScanVC{
    
    [Untis judgeIsHaveCamerCompleteBlock:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                YHScanQRCodeVC *vc = [[YHScanQRCodeVC alloc] init];
                [[AppDelegate shareAppDelegate].navigationCtrl pushViewController:vc animated:YES];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"“APP”没有获得照相机的使用权限,请在设置中开启「照相机」" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [actionSheet addAction:action1];
                [actionSheet addAction:cancleAction];
                [self presentViewController:actionSheet animated:YES completion:nil];
            });
        }
    }];
    
    
}

-(void)goToCameraComplain{
    [Untis judgeIsHaveCamerCompleteBlock:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[TZImagePickerManager shareManager] pushCameraViewController:self complete:^(UIImage * _Nonnull cameraImage) {
                    if (cameraImage) {
                        [self setPickerViewImage:cameraImage];
                    }
                }];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"“APP”没有获得照相机的使用权限,请在设置中开启「照相机」" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [actionSheet addAction:action1];
                [actionSheet addAction:cancleAction];
                [self presentViewController:actionSheet animated:YES completion:nil];
            });
        }
    }];
}


-(void)goToPickerImageComplain{
    [Untis judgeIsHaveAlbumCompleteBlock:^(BOOL granted) {
        if (granted) {
            [[TZImagePickerManager shareManager] pushPickerViewController:PickerViewControllerTypeOfImageDefault fromViewController:self selectImageNumber:1 complete:^(NSArray<UIImage *> * _Nonnull photos, NSArray * _Nonnull assets, BOOL isSelectOriginalPhoto) {
                if (photos.count) {
                    UIImage *image = [photos firstObject];
                    [self setPickerViewImage:image];
                }
            }];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"“APP”没有获得相册的使用权限,请在设置中开启「相册」" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
                [actionSheet addAction:action1];
                [actionSheet addAction:cancleAction];
                [self presentViewController:actionSheet animated:YES completion:nil];
            });
        }
    }];
}

-(void)goToLoginViewControll{
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"login"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [AppDelegate startLoginViewController];
}

-(void)goToopenFileData{
    NSArray *documentTypes = @[@"public.content",
                               @"public.text",
                               @"public.source-code",
                               @"public.image",
                               @"public.jpeg",
                               @"public.png",
                               @"com.adobe.pdf",
                               @"com.apple.keynote.key",
                               @"com.microsoft.word.doc",
                               @"com.microsoft.excel.xls",
                               @"com.microsoft.powerpoint.ppt"];
    UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
    for (int i=0; i<urls.count; i++) {
         [self openFileData:urls[i]];
    }
}

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    DLog(@"%@",url);
}

-(void)openFileData:(NSURL*)url{
    WeDocument *document = [[WeDocument alloc] initWithFileURL:url];
    __weak typeof(self) weakSelf = self;
    
    [document openWithCompletionHandler:^(BOOL success) {
        
        if (success) {
            DLog(@"文件名%@",document.docFileName);
            DLog(@"文件类型%@",document.docMIMEType);
            DLog(@"文件长度%lu",(unsigned long)document.docLength);
            DLog(@"文件资源%@",document.documentData);
            dispatch_queue_t queue = dispatch_queue_create("my_concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
            dispatch_async(queue, ^{
               // 文件上传
            });

        }  else
        {
            DLog(@"读取失败");
        }
        [document closeWithCompletionHandler:^(BOOL success) {
            
        }];
    }];
    
}

#pragma mark --- QLPreviewControllerDelegate
- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller
{
    return 1;
}
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return [NSURL fileURLWithPath:self.fileSvPath];
}
- (void)previewControllerDidDismiss:(QLPreviewController *)controller
{
 
}

-(void)setPickerViewImage:(UIImage *)image{
    self.pickerImageV.image = image;
}

//数据路径
+ (NSString *)XH_getDocumentDir{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}

@end