// // RAYTPlayer.m // iSales-UWAVER // // Created by Rui Zhang on 11/26/19. // Copyright © 2019 United Software Applications, Inc. All rights reserved. // #import "RAYTPlayer.h" @interface RAYTPlayer () //@property (strong, nonatomic) WKWebView *wkwebView; //@property (nonatomic,strong) NSDictionary *currentParams; //@property (nonatomic,weak) RAProgressHUD *hud; //@property (nonatomic,copy) NSString *url; //@property (nonatomic,assign) BOOL firstLoad; @end @implementation RAYTPlayer - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self initWKWebView]; [self initMessageHandler]; } return self; } - (instancetype)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; if (self) { [self initWKWebView]; [self initMessageHandler]; } return self; } - (void)layoutSubviews { [super layoutSubviews]; self.wkwebView.frame = self.bounds; } -(void) initWKWebView { WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; WKPreferences *preferences = [WKPreferences new]; preferences.javaScriptCanOpenWindowsAutomatically = false; // preferences.minimumFontSize = 40.0; configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll; configuration.allowsInlineMediaPlayback = true; configuration.allowsPictureInPictureMediaPlayback=false; configuration.preferences = preferences; _wkwebView = [[WKWebView alloc] initWithFrame:self.bounds configuration:configuration]; self.wkwebView.hidden=YES; // self.wkwebView.UIDelegate = self; self.wkwebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); self.wkwebView.navigationDelegate = self; self.wkwebView.scrollView.bounces = false; [self addSubview:self.wkwebView]; // __weak typeof(self) weakSelf = self; // [self.wkwebView.scrollView setEmptyContentViewBackgroupColor:UIColor.whiteColor]; // self.wkwebView.scrollView.emptyView = [RAEmptyView emptyViewWithTitle:@"can not reach the server.\ntap to reload" clickHandler:^(id sender) { // [weakSelf LoadFromURL:weakSelf.url]; // }]; // self.firstLoad = YES; } -(void)LoadWithVid:(NSString *)vid { if(self.wkwebView==nil) return; NSString * replacement = [NSString stringWithFormat:@"src=\"https://www.youtube.com/embed/%@\"",vid]; NSError *error; NSString *htmlStr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"ytplayer" ofType:@"html"]encoding:NSUTF8StringEncoding error: & error]; htmlStr=[htmlStr stringByReplacingOccurrencesOfString:@"src=replacement" withString:replacement]; // NSString *htmlStr1=@"abc def ggg"; // [htmlStr stringByReplacingOccurrencesOfString:@"src=replacement" withString:replacement]; // NSString* new_url = [NSString stringWithFormat:@"https://www.youtube.com/embed/%@?playsinline=1",vid]; // [self.wkwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:new_url]]]; [self.wkwebView loadHTMLString:htmlStr baseURL:nil]; self.wkwebView.hidden=NO; } -(void)LoadFromURL:(NSString *)vid { if(self.wkwebView==nil) return; NSString* url = [NSString stringWithFormat:@"https://www.youtube.com/embed/%@?playsinline=1",vid]; NSURL* U=[NSURL URLWithString:url]; NSURLRequest* request=[[NSURLRequest alloc]initWithURL:U cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0f]; [self.wkwebView loadRequest:request]; } -(void) initMessageHandler { // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"CamScan"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Location"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Share"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"JumpTo"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"ViewImage"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"PostDialog"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Photo"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Email"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Preview"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Navigation"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"DatetimePicker"]; // //// [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"UpdateBadge"]; // // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"Signature"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"SelectContact"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"requestApplicationInfo"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"cleanCache"]; // // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"login"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"logout"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"UpdateBadge"]; // [self.wkwebView.configuration.userContentController addScriptMessageHandler:self name:@"QueryLaunchNotification"]; // // // } -(void)destroyMessageHandler { // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"CamScan"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"JumpTo"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"ViewImage"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"PostDialog"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Photo"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Email"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Preview"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Navigation"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"DatetimePicker"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"Signature"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"SelectContact"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"requestApplicationInfo"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"cleanCache"]; // // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"login"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"logout"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"UpdateBadge"]; // [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"QueryLaunchNotification"]; } - (void)dealloc { [self destroyMessageHandler]; } #pragma mark - Setter - (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)contentInsetAdjustmentBehavior { self.wkwebView.scrollView.contentInsetAdjustmentBehavior = contentInsetAdjustmentBehavior; } // //#pragma mark - Private // //- (UIViewController *)ra_viewController { // return [RAUtils getViewController:self]; //} // //- (void)ra_openPhotoLibrary:(NSDictionary *)params { // // UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; // imagePicker.delegate = self; // imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; // imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical; // imagePicker.allowsEditing = YES; // [self.ra_viewController presentViewController:imagePicker animated:YES completion:nil]; // self.currentParams = params; //} // //- (void)ra_openCamera:(NSDictionary *)params { // // RACameraViewController *cameraVC = [RACameraViewController viewControllerFromStoryboard]; // cameraVC.completion = ^(UIImage *image) { // // image = [UIImage img_compress:image kbsize:1024]; // NSData *data = UIImageJPEGRepresentation(image, 1.0); //// NSString *name = NSUUID.UUID.UUIDString; //// NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:name]; //// [data writeToFile:path atomically:NO]; // // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]]; // // [self returnToWebPage:params value:imageSource]; // }; // // cameraVC.fromVC = self.ra_viewController; // [self.ra_viewController.navigationController pushViewController:cameraVC animated:YES]; //} // //- (void)ra_openQRCodeScanner:(NSDictionary *)params { // // RAQRCodeScannerViewController *scanVC = [RAQRCodeScannerViewController viewControllerFromStoryboard]; // // scanVC.QRCodeViewControllerDidCompletion = ^(RAQRCodeScannerViewController *qrcodeViewController, NSString *value) { // // [self returnToWebPage:params value:value]; // [qrcodeViewController.navigationController popViewControllerAnimated:YES]; // }; // // scanVC.QRCodeViewControllerDidCanceled = ^(RAQRCodeScannerViewController *qrcodeViewController) { // // [qrcodeViewController.navigationController popViewControllerAnimated:YES]; // }; // // [self.ra_viewController.navigationController pushViewController:scanVC animated:YES]; //} // // //- (void)ra_previewDocument:(NSDictionary *)params { // /** // cc = "test1@abc.com,test2@abc.com"; // content = content; // receipt = "test@abc.com"; // subject = "email subject"; // url = "http://10.0.0.4:8080/backend_test/test.pdf"; // */ // // NSString *urlStr = [params objectForKey:@"url"]; //// urlStr = @"http://192.168.0.130/ios.pdf"; // if (urlStr) { // // RAProgressHUD *hud = [RAProgressHUD showHUDOnView:self.ra_viewController.view]; // // // 先下载下来,否则QuickLook分享要崩溃 // dispatch_async(dispatch_get_global_queue(0, 0), ^{ // // NSString *tmpDir = NSTemporaryDirectory(); // // [RADataProvider GET_DownloadFile:urlStr toFolder:tmpDir progressHandler:^(NSURLSessionTask *task, double progress) { // // NSLog(@"download %@ progress %f", urlStr.lastPathComponent, progress); // // } completionHandler:^(NSMutableDictionary *result) { // // dispatch_async(dispatch_get_main_queue(), ^{ // // [hud dismiss:^{ // // int resultCode = [[result objectForKey:@"result"] intValue]; // if (resultCode == RESULT_TRUE) { // // NSString *path = [result objectForKey:@"path"]; // // RAPreviewController *vc = [RAPreviewController ra_previewControllerWithURL:[NSURL fileURLWithPath:path]]; // [self.ra_viewController presentViewController:vc animated:YES completion:nil]; // // } else { // // NSString *msg = [result objectForKey:@"msg"]; // [RAUtils message_alert:msg title:NSLocalizedString(@"warning_title", nil) controller:self.ra_viewController]; // // } // // }]; // // }); // // }]; // }); // // } //} // //- (void)ra_mail:(NSDictionary *)params { // // /** // // cc = "test1@abc.com,test2@abc.com"; // content = content; // receipt = "test@abc.com"; // subject = "email subject"; // // */ // MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; // // if(mc==nil) // { // return; // } // // NSString *subject = [params objectForKey:@"subject"]; // NSString *receipt = [params objectForKey:@"receipt"]; // NSString *content = [params objectForKey:@"content"]; // NSString *cc = [params objectForKey:@"cc"]; // // mc.mailComposeDelegate = self; // [mc setSubject:subject]; // // // [mc setToRecipients:[receipt componentsSeparatedByString:@","]]; // [mc setCcRecipients:[cc componentsSeparatedByString:@","]]; // // if(!content) // content=@""; // // NSString* htmlbody = [NSString stringWithFormat:@"

%@

",content]; // // [mc setMessageBody:htmlbody isHTML:YES]; // // //// NSString* filename =self.filename; //// //// NSString *filePath = self.url; //// NSData *data = [NSData dataWithContentsOfFile:filePath]; //// //// // if(self.attachment_name.length>0) //// // filename = self.attachment_name; //// [mc addAttachmentData:data mimeType:@"application/pdf" fileName:filename]; // // [self.ra_viewController presentViewController:mc animated:YES completion:nil]; // self.currentParams = params; //} // //- (void)ra_share:(NSDictionary *)params { // // // // // 设置分享内容 // //// NSString *content = [params objectForKey:@"content"]; //// NSString *imageURL = [params objectForKey:@"image"]; //// NSString *title = [params objectForKey:@"title"]; // NSString *url = [params objectForKey:@"url"]; // // NSArray *activityItems = @[[NSURL URLWithString:url]]; // // // 服务类型控制器 // UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:@[]]; // // _activityViewController = activityViewController; // // activityViewController.excludedActivityTypes = @[UIActivityTypeMail]; // activityViewController.modalInPopover = true; // // // 选中分享类型 // [activityViewController setCompletionWithItemsHandler:^(NSString * __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){ // // 显示选中的分享类型 // NSLog(@"act type %@",activityType); // //// if (completed) { //// NSLog(@"ok"); //// }else { //// NSLog(@"not ok"); //// } // NSMutableDictionary *shareResult = [NSMutableDictionary dictionary]; // if (!activityType) { // activityType = @"cancel"; // } // shareResult[@"to"] = [activityType componentsSeparatedByString:@"."].lastObject; // shareResult[@"completed"] = @(completed); // if (activityError) { // shareResult[@"error"] = activityError.localizedDescription; // } // // [self returnToWebPage:params value:[RAConvertor dict2string:shareResult]]; // // }]; // // [self.ra_viewController presentViewController:activityViewController animated:YES completion:nil]; //} // //- (void)ra_viewPhotos:(NSDictionary *)params { // // NSArray *urlArr = [params objectForKey:@"images"]; // NSUInteger index = [[params objectForKey:@"index"] integerValue]; // // NSMutableArray *mArr = [NSMutableArray array]; // for (NSString *url in urlArr) { // // RAPhotoModel *model = [RAPhotoModel new]; // model.url = url; // // [mArr addObject:model]; // } // // // RAPhotoPreviewController *previewController = [RAPhotoPreviewController ra_photoPreviewControllerWithPhotoItems:mArr offset:index]; // // [self.ra_viewController presentViewController:previewController animated:YES completion:nil]; //} // //- (void)ra_navigate:(NSDictionary *)params { // // NSString *name = [params objectForKey:@"name"]; // NSString *addr = [params objectForKey:@"address"]; // // [RAMapNavigateHandler ra_navigate:addr withTitle:name viewController:self.ra_viewController]; //} // //- (void)ra_signature:(NSDictionary *)params { // // __weak typeof(self) weakSelf = self; // SignatureViewController *signatureVC = [SignatureViewController ra_signatureViewControllerWithCompletion:^(UIImage *image) { // // NSData *data = UIImageJPEGRepresentation(image, 1.0); // // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]]; // // [weakSelf returnToWebPage:params value:imageSource]; // // }]; // // [self.ra_viewController.navigationController pushViewController:signatureVC animated:NO]; //} // //- (void)ra_dateTimePicker:(NSDictionary *)params { // // NSString *type = [params objectForKey:@"type"]; // NSString *value = [params objectForKey:@"value"]; // NSString *title = [params objectForKey:@"title"]; // // NSString *format = @"MM/dd/yyyy"; // UIDatePickerMode mode = UIDatePickerModeDate; // //// type = @"dateTime"; //// value = @"09/22/1028 14:44:24"; // // if ([type isEqualToString:@"date"]) { // // } else if ([type isEqualToString:@"time"]) { // // format = @"HH:mm:ss"; // mode = UIDatePickerModeTime; // // } else if ([type isEqualToString:@"dateTime"]) { // // format = @"MM/dd/yyyy HH:mm:ss"; // mode = UIDatePickerModeDateAndTime; // } // // NSDateFormatter *dateFormatter = [NSDateFormatter new]; // dateFormatter.dateFormat = format; // NSDate *date = [dateFormatter dateFromString:value]; // // __weak typeof(self) weakSelf = self; // [RADatePickerViewController presentDatePicker:self.ra_viewController title:title dateMode:mode defaultDate:date withSetBlk:^(NSDate *date) { // // NSString *dateStr = [dateFormatter stringFromDate:date]; // [weakSelf returnToWebPage:params value:dateStr]; // }]; //} // //- (void)ra_selectContact:(NSDictionary *)params { // // __weak typeof(self) weakSelf = self; // [[RAContactHelper defaultHelper] showContactPickerByViewController:self.ra_viewController withComplete:^(BOOL canceled, NSArray *contacts) { // // if (!canceled) { // // NSMutableArray *contactArray = [NSMutableArray array]; // for (CNContact *contact in contacts) { // // NSMutableDictionary *contactDictionary = [NSMutableDictionary dictionary]; // NSLog(@"========================================================="); // // givenName middleName familyName // NSString *givenName = [self adjustNilString:contact.givenName]; // NSString *middleName = [self adjustNilString:contact.middleName]; // NSString *familyName = [self adjustNilString:contact.familyName]; // NSString *name = [NSString stringWithFormat:@"%@ %@ %@", givenName, middleName, familyName]; // // NSLog(@"=======================Contact Name======================="); // NSLog(@"%@",name); // contactDictionary[@"name"] = name; // // // organizationName departmentName jobTitle // NSString *organizationName = [self adjustNilString:contact.organizationName]; // NSString *departmentName = [self adjustNilString:contact.departmentName]; // NSString *jobTitle = [self adjustNilString:contact.jobTitle]; // NSString *job = [NSString stringWithFormat:@"%@ %@ %@", organizationName, departmentName, jobTitle]; // // NSLog(@"=======================Contact Job======================="); // NSLog(@"%@",job); // contactDictionary[@"job"] = @[job]; // // // phoneNumbers emailAddresses postalAddresses urlAddresses // // NSMutableArray *phoneArray = [NSMutableArray array]; // NSMutableArray *faxArray = [NSMutableArray array]; // NSLog(@"=======================Phone Number======================="); // NSArray*> *phoneNumbers = contact.phoneNumbers; // for (CNLabeledValue *labeledValue in phoneNumbers) { // // CNPhoneNumber *phoneNumber = labeledValue.value; // NSString *label = [CNLabeledValue localizedStringForLabel:labeledValue.label]; // NSLog(@"%@ %@", label, phoneNumber.stringValue); // // if ([labeledValue.label.lowercaseString containsString:@"fax"]) { // [faxArray addObject:phoneNumber.stringValue]; // } else { // [phoneArray addObject:phoneNumber.stringValue]; // } // } // contactDictionary[@"phone"] = phoneArray; // contactDictionary[@"fax"] = faxArray; // // NSMutableArray *emailArray = [NSMutableArray array]; // NSLog(@"=======================Email Address======================="); // NSArray*> *emailAddresses = contact.emailAddresses; // for (CNLabeledValue *labeledValue in emailAddresses) { // // NSString *email = labeledValue.value; // NSString *label = [CNLabeledValue localizedStringForLabel:labeledValue.label]; // NSLog(@"%@ %@", label, email); // [emailArray addObject:email]; // } // contactDictionary[@"email"] = emailArray; // // NSMutableArray *addressArray = [NSMutableArray array]; // NSLog(@"=======================Postal Number======================="); // NSArray*> *postalAddresses = contact.postalAddresses; // for (CNLabeledValue *labeledValue in postalAddresses) { // // NSString *label = [CNLabeledValue localizedStringForLabel:labeledValue.label]; // CNPostalAddress *postalAddress = labeledValue.value; // NSString *postalCode = [self adjustNilString:postalAddress.postalCode]; // NSString *country = [self adjustNilString:postalAddress.country]; // NSString *state = [self adjustNilString:postalAddress.state]; // NSString *city = [self adjustNilString:postalAddress.city]; // NSString *street = [self adjustNilString:postalAddress.street]; // // NSMutableDictionary *addressDic = [NSMutableDictionary dictionary]; // addressDic[@"postalCode"] = postalCode; // addressDic[@"country"] = country; // addressDic[@"state"] = state; // addressDic[@"city"] = city; // addressDic[@"street"] = street; // // [addressArray addObject:addressDic]; // NSLog(@"%@ %@ %@ %@ %@ %@", label, postalCode, country, state, city, street); // } // contactDictionary[@"address"] = addressArray; // // NSMutableArray *urlArray = [NSMutableArray array]; // NSLog(@"=======================URL Address======================="); // NSArray*> *urlAddresses = contact.urlAddresses; // for (CNLabeledValue *labeledValue in urlAddresses) { // // NSString *url = labeledValue.value; // NSString *label = [CNLabeledValue localizedStringForLabel:labeledValue.label]; // NSLog(@"%@ %@", label, url); // // [urlArray addObject:url]; // } // contactDictionary[@"url"] = urlArray; // // NSLog(@"**********************************************************"); // // [contactArray addObject:contactDictionary]; // } // // // return // // NSString *jsonString = [RAConvertor DataTOjsonString:contactArray]; // [weakSelf returnToWebPage:params value:jsonString]; // // NSLog(@"%@", jsonString); // } // // }]; //} // //- (void)ra_requestAppInfo:(NSDictionary *)params { // // AppDelegate *delagate =(AppDelegate *) [[UIApplication sharedApplication]delegate]; // // NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary]; // NSString *ver = [infoDic objectForKey:@"CFBundleShortVersionString"]; // NSString *build = [infoDic objectForKey:@"CFBundleVersion"]; // NSString *appVer = [NSString localizedStringWithFormat:@"Ver: %@ build %@",ver,build]; // // NSMutableDictionary * ret = [NSMutableDictionary new]; // ret[@"appVer"]=appVer; // ret[@"apnToken"]=delagate.apnToken ; // // NSString* Sret=[RAConvertor dict2string:ret]; // [self returnToWebPage:params value:Sret]; //} // //- (void)ra_queryLaunchNotification:(NSDictionary *)params { // // AppDelegate *delagate =(AppDelegate *) [[UIApplication sharedApplication]delegate]; // //// NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary]; //// NSString *ver = [infoDic objectForKey:@"CFBundleShortVersionString"]; //// NSString *build = [infoDic objectForKey:@"CFBundleVersion"]; //// NSString *appVer = [NSString localizedStringWithFormat:@"Ver: %@ build %@",ver,build]; //// //// NSMutableDictionary * ret = [NSMutableDictionary new]; //// ret[@"appVer"]=appVer; //// ret[@"apnToken"]=delagate.apnToken ; //// //// NSString* Sret=[RAConvertor dict2string:ret]; // [self returnToWebPage:params value:delagate.launchNotification]; // delagate.launchNotification = nil; // //} // //- (void)ra_cleanCache:(NSDictionary *)params { // // /** // // // On-disk caches. // WKWebsiteDataTypeDiskCache API_AVAILABLE(macosx(10.11), ios(9.0)); // // // In-memory caches. // WKWebsiteDataTypeMemoryCache API_AVAILABLE(macosx(10.11), ios(9.0)); // // // HTML offline web application caches. // WKWebsiteDataTypeOfflineWebApplicationCache API_AVAILABLE(macosx(10.11), ios(9.0)); // // // Cookies. // WKWebsiteDataTypeCookies API_AVAILABLE(macosx(10.11), ios(9.0)); // // // HTML session storage. // WKWebsiteDataTypeSessionStorage API_AVAILABLE(macosx(10.11), ios(9.0)); // // // HTML local storage. // WKWebsiteDataTypeLocalStorage API_AVAILABLE(macosx(10.11), ios(9.0)); // // // WebSQL databases. // WKWebsiteDataTypeWebSQLDatabases API_AVAILABLE(macosx(10.11), ios(9.0)); // // // IndexedDB databases. // WKWebsiteDataTypeIndexedDBDatabases API_AVAILABLE(macosx(10.11), ios(9.0)); // // */ // // NSArray *typeArr = @[ // WKWebsiteDataTypeDiskCache, // WKWebsiteDataTypeMemoryCache, // WKWebsiteDataTypeOfflineWebApplicationCache, // WKWebsiteDataTypeLocalStorage, // WKWebsiteDataTypeWebSQLDatabases, // WKWebsiteDataTypeIndexedDBDatabases // ]; // NSSet *typeSet = [NSSet setWithArray:typeArr]; // NSDate *dateSince = [NSDate dateWithTimeIntervalSince1970:0]; // // [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:typeSet modifiedSince:dateSince completionHandler:^{ // [self returnToWebPage:params value:@""]; // }]; //} // //- (void)ra_handleLogin:(NSString *)user password:(NSString *)password { // // if (self.delegate && [self.delegate respondsToSelector:@selector(webview:didLogin:password:)]) { // [self.delegate webview:self didLogin:user password:password]; // } //} // //- (void)ra_handleLogout { // // if (self.delegate && [self.delegate respondsToSelector:@selector(webviewDidLogout:)]) { // [self.delegate webviewDidLogout:self]; // } //} #pragma mark - player //- (void)stringFromEvaluatingJavaScript:(NSString *)jsToExecute { // // return [self.wkwebView stringByEvaluatingJavaScriptFromString:jsToExecute]; // // //[self.wkwebView evaluateJavaScript:jsToExecute completionHandler:^(id _Nullable result, NSError * _Nullable error) { // NSLog(@"%@----%@",result, error); // }]; // //} - (void)stopVideo { [self.wkwebView reload]; } #pragma mark - Utils - (NSString *)adjustNilString:(NSString *)str { if (str) { return str; } return @""; } //- (void)ra_injectJS:(NSString *)js { // //// NSStringEncoding encoding = NSUTF8StringEncoding; //// NSString *js = [NSString stringWithContentsOfFile:@"/Users/macmini1/eclipse-workspace/MyWeb/WebContent/JS/Interface.js" usedEncoding:&encoding error:nil]; // // if (js) { // [self.wkwebView evaluateJavaScript:js completionHandler:^(id _Nullable result, NSError * _Nullable error) { // NSLog(@"create JS %@ Error: %@", result, error); // }]; // } //} // //#pragma mark - Web Callback // //-(void) returnToWebPage:(NSDictionary*)params value:(NSString*)value //{ // if(![params isNull:@"returnid"] ) // { // // [self webPageReturn:params[@"returnid"] value:value]; // // }else if(![params isNull:@"callback"]) // { // [self webPageCallback:params caller:params[@"id"] value:value]; // } //} //-(void) webPageCallback:(NSDictionary*)params caller:(NSString*) callerid value:(NSString*)value //{ //// NSString* caller = [NSString stringWithFormat:@"'%@'",callerid]; // NSString *caller = [callerid ra_stringByEscapingForJavascriptWithDelimiter:'\'' wrapWithDelimiters:YES]; // if(value==nil) // value=@""; //// if([value isKindOfClass:NSString.class]) // { //// value =[NSString stringWithFormat:@"'%@'",value]; // value = [(NSString *)value ra_stringByEscapingForJavascriptWithDelimiter:'\'' wrapWithDelimiters:YES]; // } // // NSString *jsStr = [NSString stringWithFormat:params[@"callback"],caller.UTF8String,value.UTF8String]; // [self.wkwebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) { // NSLog(@"%@----%@",result, error); // }]; //} //-(void) webPageReturn:(NSString*) returnid value:(NSObject*)value //{ // if (returnid && value) { // // returnid = [returnid ra_stringByEscapingForJavascriptWithDelimiter:'\'' wrapWithDelimiters:YES]; // value = [value.description ra_stringByEscapingForJavascriptWithDelimiter:'\'' wrapWithDelimiters:YES]; // NSString *jsStr = [NSString stringWithFormat:@"document.getElementById(%@).value = %@;",returnid,value]; // //// NSString *jsStr = [NSString stringWithFormat:@"document.getElementById(\"%@\").value = \"%@\";",returnid,value]; // [self.wkwebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) { // NSLog(@"%@----%@",result, error); // }]; // // } //} // //- (void)evaluateJs:(NSString *)js completionHandler:(void (^) (id result, NSError *error))handler { // [self.wkwebView evaluateJavaScript:js completionHandler:handler]; //} // //#pragma mark - MFMailComposeViewControllerDelegate delegate // //- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error { // NSString *resultStr = nil; // switch (result) // { // case MFMailComposeResultCancelled: // resultStr = @"email canceled"; // break; // case MFMailComposeResultSaved: // resultStr = @"email saved"; // break; // case MFMailComposeResultSent: // resultStr = @"email send"; // break; // case MFMailComposeResultFailed: // resultStr = [NSString stringWithFormat:@"email error: %@",[error localizedDescription]]; // break; // default: // break; // } // // [self returnToWebPage:self.currentParams value:resultStr]; // self.currentParams = nil; // // [controller dismissViewControllerAnimated:YES completion:nil]; //} // // //#pragma mark - UIImagePickerControllerDelegate // //- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // // if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) { // // UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; // image = [UIImage img_compress:image kbsize:1024]; // // [picker dismissViewControllerAnimated:YES completion:nil]; // // NSData *data = UIImageJPEGRepresentation(image, 1.0); // NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]]; // // [self returnToWebPage:self.currentParams value:imageSource]; // self.currentParams = nil; // // } //} // //- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { // [picker dismissViewControllerAnimated:YES completion:nil]; //} //#pragma mark - WKUIDelegate //- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler //{ // // UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert]; // [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { // if(completionHandler) // completionHandler(); // }]]; // // UIViewController* vc=[RAUtils getViewController:self]; // [vc presentViewController:alert animated:YES completion:nil]; // //// UIViewController* vc=[self getViewController]; //// [vc presentViewController:alert animated:YES completion:nil]; //} //-(UIViewController*) getViewController //{ // for (UIView* next = [self superview]; next; next = next.superview) { // UIResponder* nextResponder = [next nextResponder]; // if ([nextResponder isKindOfClass:[UIViewController class]]) { // return (UIViewController*)nextResponder; // } // } // return nil; //} // //#pragma mark - WKScriptMessageHandler //- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message //{ // // message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull. // NSLog(@"%@",message.name); // NSLog(@"body:%@",message.body); // // // NSDictionary* params=[RAConvertor string2dict:message.body]; //// RAConvertor // if ([message.name isEqualToString:@"CamScan"]) { // // [self handleCamScan:params]; // } else if ([message.name isEqualToString:@"Location"]) { // // [self handleLocation:params]; // } else if ([message.name isEqualToString:@"Share"]) { // // [self handleShare:params]; // } else if ([message.name isEqualToString:@"JumpTo"]) { // // // [self handleJumpTo:params]; // } else if ([message.name isEqualToString:@"ViewImage"]) { // // // [self handleViewImage:params]; // } else if ([message.name isEqualToString:@"PostDialog"]) { // // // [self handlePostDialog:params]; // }else if ([message.name isEqualToString:@"Photo"]) { // // // [self handlePhoto:params]; // }else if ([message.name isEqualToString:@"Email"]) { // // // // [self handleEmail:params]; // }else if ([message.name isEqualToString:@"Preview"]) { // // // // [self handlePreview:params]; // }else if ([message.name isEqualToString:@"Navigation"]) { // // // // [self handleNavigation:params]; // }else if ([message.name isEqualToString:@"Signature"]) { // // // // [self handleSignature:params]; // }else if ([message.name isEqualToString:@"DatetimePicker"]) { // // // // [self handleDatetimePicker:params]; // } else if ([message.name isEqualToString:@"SelectContact"]) { // // [self handleSelectContact:params]; // } else if ([message.name isEqualToString:@"requestApplicationInfo"]) { // // [self handleRequestApplicationInfo: params]; // }else if ([message.name isEqualToString:@"QueryLaunchNotification"]) { // // [self ra_queryLaunchNotification: params]; // } // // else if ([message.name isEqualToString:@"UpdateBadge"]) { // // [self handleUpdateBadge: params]; // } else if ([message.name isEqualToString:@"cleanCache"]) { // // [self handleCleanCache:params]; // } else if ([message.name isEqualToString:@"login"]) { // // [self handleLogin:params]; // } else if ([message.name isEqualToString:@"logout"]) { // // [self handleLogout]; // } // else // { // NSLog(@"%@",params); // } //} // //- (void)handleDatetimePicker:(NSDictionary *)params //{ // // // NSLog(@"handleDatetimePicker %@",params); // // [self ra_dateTimePicker:params]; //} // //- (void)handleSignature:(NSDictionary *)params //{ // [self ra_signature:params]; //} // //- (void)handleCamScan:(NSDictionary *)params //{ // [self ra_openQRCodeScanner:params]; //} // //- (void)handleLocation:(NSDictionary *)params //{ // [self returnToWebPage:params value:@"abc,def,'aaa"]; //} // //- (void)handleShare:(NSDictionary *)params //{ // [self ra_share:params]; //} // //- (void)handleViewImage:(NSDictionary *)params //{ // [self ra_viewPhotos:params]; //} // //- (void)handlePostDialog:(NSDictionary *)params //{ // UIAlertController *alert = [UIAlertController alertControllerWithTitle:params[@"title"] message:params[@"message"] preferredStyle:UIAlertControllerStyleAlert]; // // NSArray* arr_btns=params[@"buttons"]; // for(int i=0;i" baseURL:bundleURL]; // // [self.wkwebView.scrollView showEmpty]; // } //} // //- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation //{ // NSLog(@"%s",__func__); // @synchronized (self) { // if (self.hud) { // [self.hud dismiss]; // self.hud = nil; // self.firstLoad = NO; // } // // if (self.delegate && [self.delegate respondsToSelector:@selector(webviewDidFinishLoading:error:)]) { // [self.delegate webviewDidFinishLoading:self error:nil]; // } // // // self.wkwebView.scrollView.scrollEnabled = NO; // [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id result, NSError *_Nullable error) { // // NSLog(@"web page height:%@",result); // //result 就是加载完成后 webView的实际高度 // //获取后返回重新布局 // // }]; // } // //// NSStringEncoding encoding = NSUTF8StringEncoding; //// NSString *js = [NSString stringWithContentsOfFile:@"/Users/macmini1/eclipse-workspace/MyWeb/WebContent/JS/Interface.js" usedEncoding:&encoding error:nil]; //// [self ra_injectJS:js]; //// // // css // // /Users/macmini1/eclipse-workspace/MyWeb/WebContent/test.css //// NSString *cssJs = [NSString stringWithFormat:]; // //} // //- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { // NSLog(@"%s",__func__); //} // //- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { // NSLog(@"%s",__func__); //} // //- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler //{ // NSLog(@"%s",__func__); // decisionHandler(WKNavigationResponsePolicyAllow); //} #pragma mark - WKNavigationDelegate - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation { NSLog(@"%s",__func__); } - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler { NSLog(@"%s",__func__); //1)获取trust object SecTrustRef trust = challenge.protectionSpace.serverTrust; SecTrustResultType result; //2)SecTrustEvaluate对trust进行验证 OSStatus status = SecTrustEvaluate(trust, &result); // CFArrayRef defaultPolicies = NULL; // SecTrustCopyPolicies(trust, &defaultPolicies); // NSLog(@"default policies: %@",(__bridge id)defaultPolicies); NSMutableArray *policies = [NSMutableArray array]; [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; SecTrustSetPolicies(trust, (__bridge CFArrayRef)policies); if (status == errSecSuccess && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified)) { //3)验证成功,生成NSURLCredential凭证cred,告知challenge的sender使用这个凭证来继续连接 NSURLCredential *cred = [NSURLCredential credentialForTrust:trust]; [challenge.sender useCredential:cred forAuthenticationChallenge:challenge]; if (completionHandler) { completionHandler(NSURLSessionAuthChallengeUseCredential,cred); // 使用证书 } } else { [challenge.sender cancelAuthenticationChallenge:challenge]; //4)验证失败,取消这次验证流程 if (completionHandler) { completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge,nil); // 忽略证书 } } } - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { NSLog(@"%@",error); } //禁止链接跳转 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSLog(@"%s",__func__); NSLog(@"navigationAction = %@, \r!!!!!!!!!!!!!!!!!!!!!!\n request = %@",navigationAction,navigationAction.request.URL); // NSURLRequest * request = navigationAction.request; return decisionHandler(WKNavigationActionPolicyAllow); // if ([request.URL.host isEqual: self.originURL.host]) { // return decisionHandler(WKNavigationActionPolicyAllow); // } else if ([request.URL.scheme isEqual:@"ytplayer"]) { // [self notifyDelegateOfYouTubeCallbackUrl:request.URL]; // return decisionHandler(WKNavigationActionPolicyCancel); // } else if ([request.URL.scheme isEqual: @"http"] || [request.URL.scheme isEqual:@"https"]) { // if( [self handleHttpNavigationToUrl:request.URL]) // return decisionHandler(WKNavigationActionPolicyAllow); // else // return decisionHandler(WKNavigationActionPolicyCancel); // } // return decisionHandler(WKNavigationActionPolicyAllow); } // //- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { // NSLog(@"%s",__func__); // @synchronized (self) { // [self.wkwebView.scrollView hideEmpty]; // if (self.firstLoad && !self.hud) { // self.hud = [RAProgressHUD showHUDOnView:self.ra_viewController.view]; // } // if (self.delegate && [self.delegate respondsToSelector:@selector(webviewDidStarLoading:)]) { // [self.delegate webviewDidStarLoading:self]; // } // } //} // //- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { // NSLog(@"%s",__func__); // NSLog(@"error: %@", error.localizedDescription); // @synchronized (self) { // if (self.hud) { // [self.hud dismiss]; // self.hud = nil; // } // // if (self.delegate && [self.delegate respondsToSelector:@selector(webviewDidFinishLoading:error:)]) { // [self.delegate webviewDidFinishLoading:self error:error]; // } // // // NSURL *bundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; // // [webView loadHTMLString:@"" baseURL:bundleURL]; // // [self.wkwebView.scrollView showEmpty]; // } //} // //- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation //{ // NSLog(@"%s",__func__); // @synchronized (self) { // if (self.hud) { // [self.hud dismiss]; // self.hud = nil; // self.firstLoad = NO; // } // // if (self.delegate && [self.delegate respondsToSelector:@selector(webviewDidFinishLoading:error:)]) { // [self.delegate webviewDidFinishLoading:self error:nil]; // } // // // self.wkwebView.scrollView.scrollEnabled = NO; // [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id result, NSError *_Nullable error) { // // NSLog(@"web page height:%@",result); // //result 就是加载完成后 webView的实际高度 // //获取后返回重新布局 // // }]; // } // // //} // //- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { // NSLog(@"%s",__func__); //} // //- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { // NSLog(@"%s",__func__); //} // //- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler //{ // NSLog(@"%s",__func__); // decisionHandler(WKNavigationResponsePolicyAllow); //} @end