// // WKWebViewController.m // YHScrollView_Test // // Created by Jim on 2021/9/4. // #import "WKWebViewController.h" #import <WebKit/WebKit.h> #import "YHScanQRCodeVC.h" #import "TZImagePickerManager.h" #import "WeDocument.h" #import "AppDelegate.h" #import "AFNetworking.h" #import "LCDownloadManager.h" #import <QuickLook/QuickLook.h> #import <CoreLocation/CoreLocation.h> #import <CoreMotion/CoreMotion.h> #import <AMapFoundationKit/AMapFoundationKit.h> #import <AMapLocationKit/AMapLocationKit.h> #import "ZZWHudHelper.h" #import "MyLatLng.h" #import "HLLWebViewController.h" #define getUserInfo @"getUserInfo" #define getLocationInfo @"getLocationInfo" #define goBackLogin @"goBackLogin" #define getGetrotateInfo @"getGetrotateInfo" #define getScanInfo @"getScanInfo" #define getPhotoInfo @"getPhotoInfo" #define getFileInfo @"getFileInfo" #define getPictureInfo @"getPictureInfo" #define stopGetGetrotateInfo @"stopGetGetrotateInfo" #define browsePdf @"browsePdf" @interface WKWebViewController ()<WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate,UIDocumentPickerDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate,CLLocationManagerDelegate,YHScanQRCodeVCDelegate,AMapLocationManagerDelegate>{ } @property (nonatomic, strong) WKWebView *webView; @property (nonatomic, strong) UIView *progressBackView; @property (nonatomic, strong) UIProgressView *myProgressView; @property (nonatomic , strong) UIImageView *pickerImageV; @property (nonatomic, strong) AFHTTPRequestOperation *operation; @property (nonatomic, strong) NSString *fileSvPath; @property (nonatomic, strong) CLLocationManager *locationManager; @property (nonatomic, strong) AMapLocationManager *locationManager2; @property (nonatomic, strong) NSString *jsMethodName; @property (nonatomic, strong) CMMotionManager *motionManager; @property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock; @end @implementation WKWebViewController - (void)viewDidLoad { [super viewDidLoad]; self.zx_hideBaseNavBar = YES; /* 加载WKWebView之前 先清空缓存 */ [self clearWebViewCache]; [self initProgressBackView]; [self initView]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // addScriptMessageHandler 很容易导致循环引用 // 控制器 强引用了WKWebView,WKWebView copy(强引用了)configuration, configuration copy (强引用了)userContentController // userContentController 强引用了 self (控制器) [self.webView.configuration.userContentController addScriptMessageHandler:self name:getUserInfo]; //js调用获取 登录信息 [self.webView.configuration.userContentController addScriptMessageHandler:self name:getLocationInfo]; //js调用获取 定位信息 [self.webView.configuration.userContentController addScriptMessageHandler:self name:goBackLogin]; //js调用 返回登录页 [self.webView.configuration.userContentController addScriptMessageHandler:self name:getGetrotateInfo]; //js调用获取 角度信息 [self.webView.configuration.userContentController addScriptMessageHandler:self name:getScanInfo]; //js调用获取 扫码信息 [self.webView.configuration.userContentController addScriptMessageHandler:self name:getPhotoInfo]; //js调用获取 拍照信息 [self.webView.configuration.userContentController addScriptMessageHandler:self name:getFileInfo]; //js调用获取 文件 [self.webView.configuration.userContentController addScriptMessageHandler:self name:getPictureInfo]; //js调用获取 选择图片 [self.webView.configuration.userContentController addScriptMessageHandler:self name:stopGetGetrotateInfo]; //js调用获取 选择图片 [self.webView.configuration.userContentController addScriptMessageHandler:self name:browsePdf]; //js调用获取 浏览pdf } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // 因此这里要记得移除handlers [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getUserInfo]; //js调用获取 登录信息 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getLocationInfo]; //js调用获取 定位信息 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:goBackLogin]; //js调用 返回登录页 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getGetrotateInfo]; //js调用获取 角度信息 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getScanInfo]; //js调用获取 扫码信息 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getPhotoInfo]; //js调用获取 拍照信息 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getFileInfo]; //js调用获取 文件 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:getPictureInfo]; //js调用获取 选择图片 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:stopGetGetrotateInfo]; //js调用获取 选择图片 [self.webView.configuration.userContentController removeScriptMessageHandlerForName:browsePdf]; //js调用获取 浏览pdf } #pragma mark - JS调用OC -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { /** js 调用OC方法*/ NSLog(@"js 调用OC方法 %@",message.name); [self performSelector:@selector(Fish_showWebView) withObject:nil afterDelay:0]; self.jsMethodName = message.name; //登录信息 if ([message.name caseInsensitiveCompare:getUserInfo] == NSOrderedSame) { [self requestUsrInfo]; } //地理位置 if ([message.name caseInsensitiveCompare:getLocationInfo] == NSOrderedSame) { [self requestLocation]; // [self requestGetrotateInfo]; } // 手机角度 if ([message.name caseInsensitiveCompare:getGetrotateInfo] == NSOrderedSame) { [self requestGetrotateInfo]; } // 停止手机角度 if ([message.name caseInsensitiveCompare:stopGetGetrotateInfo] == NSOrderedSame) { [self stopRequestGetrotateInfo]; } //扫一扫 if ([message.name caseInsensitiveCompare:getScanInfo] == NSOrderedSame) { [self requestScan]; } //拍照 if ([message.name caseInsensitiveCompare:getPhotoInfo] == NSOrderedSame) { [self requestTokePhoto]; } //浏览pdf if ([message.name caseInsensitiveCompare:browsePdf] == NSOrderedSame) { if (message.body[browsePdf]) { [self browsePdfWithUrl:message.body[browsePdf]]; } } //选择图片 if ([message.name caseInsensitiveCompare:getPictureInfo] == NSOrderedSame) { [self requestChoosePicture]; } //上传文件 if ([message.name caseInsensitiveCompare:getFileInfo] == NSOrderedSame) { [self requestFile]; } //返回登录页 if ([message.name caseInsensitiveCompare:goBackLogin] == NSOrderedSame) { [self backLogin]; } } -(void)browsePdfWithUrl:(NSString *)urlStr{ HLLWebViewController *webViewLocalController = [[HLLWebViewController alloc]init]; NSCharacterSet *characterSet = [NSCharacterSet URLQueryAllowedCharacterSet]; NSString *encodeStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:characterSet]; webViewLocalController.webUrlString = encodeStr; [self.navigationController pushViewController:webViewLocalController animated:YES]; // [self.navigationController presentViewController:webViewLocalController animated:YES completion:nil]; } -(void)stopRequestGetrotateInfo{ [self.motionManager stopAccelerometerUpdates]; } -(void)requestGetrotateInfo{ if (self.motionManager == nil) { self.motionManager = [[CMMotionManager alloc]init]; } NSOperationQueue*queue = [[NSOperationQueue alloc]init]; //加速计 if(self.motionManager.accelerometerAvailable) { [self.motionManager startDeviceMotionUpdatesToQueue:queue withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) { if(error) { [self.motionManager stopAccelerometerUpdates]; NSLog(@"error"); }else{ double gravityX = motion.gravity.x; double gravityY = motion.gravity.y; double gravityZ = motion.gravity.z; double zTheta = atan2(gravityZ,sqrtf(gravityX * gravityX + gravityY*gravityY))/M_PI*180.0; double xyTheta = atan2(gravityX, gravityY)/M_PI*180.0; self.jsMethodName = getGetrotateInfo; [self uploadH5Message:[NSString stringWithFormat:@"%.2f",xyTheta]]; [self.motionManager stopDeviceMotionUpdates]; } }]; }else{ NSLog(@"This device has no accelerometer"); } } #pragma mark - private -(void)initProgressBackView{ self.progressBackView.hidden=NO; self.myProgressView.hidden=NO; [self.view bringSubviewToFront:self.progressBackView]; } -(void)hideProgressView{ self.myProgressView.hidden = YES; } -(void)initView{ WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init]; _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0.0, 0.0, KScreenHeight, KScreenWidth) configuration:config]; _webView.userInteractionEnabled = YES; // _webView.backgroundColor = [UIColor blackColor]; _webView.backgroundColor = [UIColor whiteColor]; _webView.navigationDelegate=self; _webView.UIDelegate = self; _webView.scrollView.showsVerticalScrollIndicator = NO; [self.view addSubview:_webView]; _webView.hidden=NO; [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; [_webView mas_remakeConstraints:^(MASConstraintMaker *make) { // make.top.mas_equalTo(KNavHeight); make.top.mas_equalTo(0); make.left.mas_equalTo(0); make.width.mas_equalTo(KScreenWidth); make.bottom.mas_equalTo(self.view).offset(0); }]; if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 11.0){ if (LocalTest) { NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil]; NSURL *fileURL = [NSURL fileURLWithPath:urlStr]; [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL]; // [self.webView loadHTMLString:@"<input accept='file/*' type='file'>" baseURL:fileURL]; }else{ NSMutableURLRequest *request = nil; // 获取毫秒时间戳,达到每次请求的url都不同,避免缓存 double currentTime = [[NSDate date] timeIntervalSince1970]; NSString *strTime = [NSString stringWithFormat:@"%.0f",currentTime]; NSString *urlStr = [NSString stringWithFormat:@"http://192.168.100.18:9500/hzapp_html/dist/#/home/workSpace/?t=%@",strTime]; request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];; [request setTimeoutInterval:10]; [self.webView loadRequest:request]; } }else{ /** long long req_timestamp= [[NSDate date] timeIntervalSince1970]*1000; NSString *req_timestampStr=[NSString stringWithFormat:@"%lld",req_timestamp]; NSDictionary *param = @{@"uid":kUid,@"channel":channel,@"version":kAPPShortVersion,@"lang":language,@"check_token":accesstoken,@"tab_type":@(tab_type),@"req_timestamp":req_timestampStr}; NSMutableString *sig = [[NSMutableString alloc] init]; [sig appendFormat:@"%@%@",[YJJhikimotoxin sortDictionaryByKet:param],@"YTSaWAQhfMwGjX8ysdxfStEZvxAVOtRL"]; NSString *sigStr = [Scorpionweed Fish_md5StringFromString:sig]; NSDictionary *dataParam = @{@"uid":kUid,@"channel":channel,@"version":kAPPShortVersion,@"lang":language,@"check_token":accesstoken,@"tab_type":@(tab_type),@"req_timestamp":req_timestampStr,@"sign":sigStr}; NSString * dataStr = [[[NSString alloc] initWithData:[dataParam jsonString] encoding:NSUTF8StringEncoding] base64EncodedString]; NSString * urlStr = [NSString stringWithFormat:@"%@?data=%@",open_task_page,dataStr]; */ NSString * urlStr = [NSString stringWithFormat:@"%@?data=%@",@"",@""]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]]; [self.webView loadRequest:request]; } [self.view addSubview:self.myProgressView]; } -(void)backLogin{ //清空所有 // NSString*appDomain = [[NSBundle mainBundle]bundleIdentifier]; // [[NSUserDefaults standardUserDefaults]removePersistentDomainForName:appDomain]; //清除token,保留密码 NSUserDefaults *defs = [NSUserDefaults standardUserDefaults]; NSDictionary *defaults = [defs dictionaryRepresentation]; for (id key in defaults) { if ([key isEqualToString:@"token"]) { [defs removeObjectForKey:key]; [defs synchronize]; }else{ NSLog(@"%@",[defs objectForKey:key]); } } //页面返回登录页 [AppDelegate startLoginViewController]; } -(void)Fish_showWebView{ //self.webView.hidden=NO; } -(void)requestTokePhoto{ [self goToCameraComplain]; } -(void)requestChoosePicture{ [self goToPickerImageComplain]; } -(void)requestUsrInfo{ NSDictionary *dic =[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]; NSString *str = [self dictionaryToJson:dic]; [self uploadH5Message:str]; } #pragma mark - WKNavigationDelegate 页面加载成功 - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { NSLog(@"webViewDidFinishLoad"); //进度条隐藏 [self hideProgressView]; [self performSelector:@selector(Fish_showWebView) withObject:nil afterDelay:0]; } //#pragma mark - 加载连接 - (void)webView:(WKWebView *)webView didFailLoadWithError:(nonnull NSError *)error{ [self performSelector:@selector(Fish_showWebView) withObject:nil afterDelay:0]; } - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { if ([self.navigationController visibleViewController] != self) { completionHandler(); return; } UIAlertController *alertController = [UIAlertController alertControllerWithTitle: @"" message: message preferredStyle: UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle: @"确认" style: UIAlertActionStyleCancel handler:^(UIAlertAction *action) { completionHandler(); }]]; if ([self.navigationController visibleViewController] == self) { [self presentViewController:alertController animated:YES completion:nil]; }else { completionHandler(); } } #pragma mark - event response // 计算wkWebView进度条 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) { CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue]; self.myProgressView.alpha = 1.0f; [self.myProgressView setProgress:newprogress animated:YES]; if (newprogress >= 0.4f) { [self.progressBackView removeFromSuperview]; [self Fish_showWebView]; } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } - (NSString*)dictionaryToJson:(NSDictionary*)dic { NSError*parseError =nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:&parseError]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } - (NSString *)noWhiteSpaceStringWithStr:(NSString *) str { NSString *newString = str; //去除掉首尾的空白字符和换行字符 newString = [newString stringByReplacingOccurrencesOfString:@"\r" withString:@""]; newString = [newString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //去除掉首尾的空白字符和换行字符使用 newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""]; // 可以去掉空格,注意此时生成的strUrl是autorelease属性的,所以不必对strUrl进行release操作! return newString; } #pragma mark --- OC调用JS方法,刷新数据 -(void)refreshData{ NSLog(@"刷新============"); NSString *javaScript=[NSString stringWithFormat:@"refreshData(%@)",@"0"]; [_webView evaluateJavaScript:javaScript completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"evaluateJavaScript完毕%@",error); }]; } -(void)goToComplete:(NSDictionary *)taskDic{ } #pragma mark --- GET - (WKWebView *)webView { if (_webView == nil) { } return _webView; } - (UIView *)progressBackView { if (_progressBackView == nil) { _progressBackView = [[UIView alloc] initWithFrame:CGRectMake(0,KNavHeight,KScreenWidth, KScreenHeight)]; _progressBackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]; [self.view addSubview:_progressBackView]; _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0,KScreenWidth, 3)]; _myProgressView.tintColor = UIColorFromRGB(0x3313025); // _myProgressView.tintColor = [UIColor lig]; _myProgressView.trackTintColor = [UIColor clearColor]; [_progressBackView addSubview:_myProgressView]; } return _progressBackView; } #pragma mark --- 清理网页缓存 -(void)clearWebViewCache{ WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore]; [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray * __nonnull records) { for (WKWebsiteDataRecord *record in records) { [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{ NSLog(@"Cookies for %@ deleted successfully",record.displayName); }]; } }]; } #pragma mark --- 相关方法 -(void)requestLocation{ // if (self.locationManager2 == nil) { // self.locationManager2 = [[AMapLocationManager alloc]init]; // self.locationManager2.delegate = self; // [self.locationManager2 setDesiredAccuracy:kCLLocationAccuracyKilometer]; // } // // if ([AMapLocationManager headingAvailable]) { // [self.locationManager2 startUpdatingHeading]; // } // // if ([CLLocationManager locationServicesEnabled]) { // if ([self getLocatoinAuth]) { // // //单次定位 // [self.locationManager2 requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) { // if (error == nil) { // NSString *lat = [NSString stringWithFormat:@"%.8f",location.coordinate.latitude]; // NSString *lng = [NSString stringWithFormat:@"%.8f",location.coordinate.longitude]; // NSDictionary *dic = @{@"lat":lat,@"lng":lng,@"addr":regeocode.formattedAddress,@"code":@"200"}; // self.jsMethodName = getLocationInfo; // [self uploadH5Message:[self dictionaryToJson:dic]]; // }else{ // NSDictionary *dic = @{@"code":@"0"}; // self.jsMethodName = getLocationInfo; // [self uploadH5Message:[self dictionaryToJson:dic]]; // // } // // }]; // } // } [self startLocation]; } -(void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager{ [locationManager requestAlwaysAuthorization]; } -(BOOL)getLocatoinAuth { BOOL isAuthNotDeteermined = [CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined; BOOL isAuthNo = [CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied || [CLLocationManager authorizationStatus]==kCLAuthorizationStatusRestricted; if ([CLLocationManager locationServicesEnabled] && isAuthNotDeteermined) { self.locationManager = [[CLLocationManager alloc] init]; [self.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:@"确定" style:UIAlertActionStyleCancel handler:nil]; [alertCtrl addAction:cancelAction]; [self presentViewController:alertCtrl animated:YES completion:nil]; return NO; } return YES; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { if ([error code] == kCLErrorDenied) { NSLog(@"访问被拒绝"); } if ([error code] == kCLErrorLocationUnknown) { NSLog(@"无法获取位置信息"); } } //开始定位 - (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]; [self.locationManager startUpdatingHeading]; } } #pragma mark -CLLocationManagerDelegate // 已经更新到用户设备朝向时调用 -(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading { // magneticHeading : 距离磁北方向的角度 // trueHeading : 真北 // headingAccuracy : 如果是负数,代表当前设备朝向不可用 if (newHeading.headingAccuracy < 0) { NSLog(@"设备未校准或受到磁场干扰"); return; } // 角度 NSLog(@"磁北极夹角%f",newHeading.magneticHeading); NSLog(@"真北极夹角%f",newHeading.trueHeading); self.jsMethodName = getGetrotateInfo; [self uploadH5Message:[NSString stringWithFormat:@"%.2f",newHeading.trueHeading]]; // 角度-> 弧度 // double radius = angle / 180.0 * M_PI; [self.locationManager2 stopUpdatingHeading]; } //定位代理经纬度回调 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { CLLocation *location = locations[0]; // NSString *lat = [NSString stringWithFormat:@"%.8f",location.coordinate.latitude]; // NSString *lng = [NSString stringWithFormat:@"%.8f",location.coordinate.longitude]; // NSDictionary *dic = @{@"lat":lat,@"lng":lng,@"addr":regeocode.formattedAddress,@"code":@"200"}; // self.jsMethodName = getLocationInfo; // [self uploadH5Message:[self dictionaryToJson:dic]]; // 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:location 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); //获取地理位置名称 NSDictionary *addressDic=placemark.addressDictionary; NSString *state=[addressDic objectForKey:@"State"]; NSString *city=[addressDic objectForKey:@"City"]; NSString *subLocality=[addressDic objectForKey:@"SubLocality"]; NSString *street=[addressDic objectForKey:@"Street"]; NSString *lat = [NSString stringWithFormat:@"%.8f",location.coordinate.latitude]; NSString *lng = [NSString stringWithFormat:@"%.8f",location.coordinate.longitude]; NSString * address = [NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,street]; NSDictionary *dic = @{@"lat":lat,@"lng":lng,@"addr":address,@"code":@"200"}; self.jsMethodName = getLocationInfo; [self uploadH5Message:[self dictionaryToJson:dic]]; NSLog(@"%@%@%@%@",state,city,subLocality,street); // [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]; } #pragma mark -CLLocationManagerDelegate // 已经更新到用户设备朝向时调用 - (void)amapLocationManager:(AMapLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{ // magneticHeading : 距离磁北方向的角度 // trueHeading : 真北 // headingAccuracy : 如果是负数,代表当前设备朝向不可用 if (newHeading.headingAccuracy < 0) { return; } // 角度 NSLog(@"磁北极夹角%f",newHeading.magneticHeading); NSLog(@"真北极夹角%f",newHeading.trueHeading); self.jsMethodName = getGetrotateInfo; [self uploadH5Message:[NSString stringWithFormat:@"%.2f",newHeading.trueHeading]]; // 角度-> 弧度 // double radius = angle / 180.0 * M_PI; [self.locationManager2 stopUpdatingHeading]; } -(void)uploadH5Message:(NSString *)str{ NSString *string = [NSString stringWithFormat:@"%@('%@')",self.jsMethodName,str]; NSLog(@"%@",string); //内容去空格 string = [self noWhiteSpaceStringWithStr:string]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW,0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [self.webView evaluateJavaScript:string completionHandler:^(id _Nullable result, NSError * _Nullable error) { NSLog(@"error = %@",error); NSLog(@"OC传值%@给js完毕",str); // [self refreshData]; }]; }); } -(void)downloadFile{ [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) YHScanQRCodeVC: (YHScanQRCodeVC *) albumController didFinishScingMediaWithResult:(NSString *)result{ [[AppDelegate shareAppDelegate].navigationCtrl popViewControllerAnimated:YES]; [self uploadH5Message:result]; } -(void)requestScan{ [Untis judgeIsHaveCamerCompleteBlock:^(BOOL granted) { if (granted) { dispatch_async(dispatch_get_main_queue(), ^{ // 扫描二维码 YHScanQRCodeVC *vc = [YHScanQRCodeVC new]; vc.delegate = self; [[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]; } -(void)requestFile{ [self goToopenFileData]; } #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{ NSData *data = UIImagePNGRepresentation(image); // NSData *data =UIImageJPEGRepresentation(image, 1.0); NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; NSString *imageString = [self noWhiteSpaceStringWithStr:encodedImageStr]; [self uploadH5Message:imageString]; } //数据路径 + (NSString *)XH_getDocumentDir{ return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; } // 记得取消监听 - (void)dealloc { if (_webView) { [_webView removeObserver:self forKeyPath:@"estimatedProgress"]; [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"GotoComplete"]; [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"showPoolsOverview"]; } } @end