最近做一個項目,開始是使用WebView與JS交互的,由於內存管理方面WebView欠佳。WKWebVIew的內存線程管理好,所以選擇使用 WKWebVIew(使用WKWebView 的缺點在於,這個控件加載的H5頁面不支持ajax請求,所以需要自己把網絡請求在OC上實現)。
一、首先說下應該注意的問題:
1.要獲取拍照或相冊的圖片,如果是iOS 10系統,需要設置訪問權限(在 Info-plist 中設置)
相機權限: Privacy - Camera Usage Description 是否允許此App使用你的相機?
相冊權限: Privacy - Photo Library Usage Description 是否允許此App訪問你的媒體資料庫?
2.WebView和WKWebView和JS互調的方法和使用的傳參類型不同
WebView 使用 (window.iosModel.getImage(JSON.stringify(parameter));//JSON.stringify(參數字符串) 這個方法是 把字符串轉換成json字符串 parameter是參數字符串
)傳值給 OC
WKWebView 使用 (window.webkit.messageHandlers.iosModel.postMessage(parameter))
3.需要特別注意的是:WKWebView 不執行JS寫的 ajax請求(WKWebView 可能由於基於 WebKit,並不會執行 C socket 相關的函數對 HTTP 請求進行處理)如果有網絡請求,需要自己用OC實現
4.使用的時候不要忘記掛上使用到的代理,和導入代理
@interface ViewController ()
5.屏蔽WebView的可選菜單(即不會出現拷貝、全選等彈出菜單)在加載完成後的代理中執行以下兩段JS
// 導航完成時,會回調(也就是頁面載入完成了) - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"66===%s", __FUNCTION__); // 禁用選中效果 [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil]; [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil]; }
二、代碼:
#import "ViewController.h" #import#import #import "SaveImage_Util.h" @interface ViewController () @property (nonatomic, strong) WKWebView *webView; @property (nonatomic, strong) UIProgressView *progressView; @end @implementation ViewController { int indextNumb;// 交替圖片名字 UIImage *getImage;//獲取的圖片 } - (void)viewDidLoad { [super viewDidLoad]; self.edgesForExtendedLayout = UIRectEdgeNone; self.automaticallyAdjustsScrollViewInsets = NO; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; // 設置偏好設置 config.preferences = [[WKPreferences alloc] init]; // 默認為0 config.preferences.minimumFontSize = 10; // 默認認為YES config.preferences.javaScriptEnabled = YES; // 在iOS上默認為NO,表示不能自動通過窗口打開 config.preferences.javaScriptCanOpenWindowsAutomatically = NO; // web內容處理池 config.processPool = [[WKProcessPool alloc] init]; // 通過JS與webview內容交互 config.userContentController = [[WKUserContentController alloc] init]; // 注入JS對象名稱AppModel,當JS通過AppModel來調用時, // 我們可以在WKScriptMessageHandler代理中接收到 [config.userContentController addScriptMessageHandler:self name:@"iosModel"]; //通過默認的構造器來創建對象 self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; // 導航代理 self.webView.navigationDelegate = self; // 與webview UI交互代理 self.webView.UIDelegate = self; NSURL *path = [[NSBundle mainBundle] URLForResource:@"testJS" withExtension:@"html"]; [self.webView loadRequest:[NSURLRequest requestWithURL:path]]; [self.view addSubview:self.webView]; // 添加KVO監聽 [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; // 添加進入條 self.progressView = [[UIProgressView alloc] init]; self.progressView.frame = self.view.bounds; [self.view addSubview:self.progressView]; self.progressView.backgroundColor = [UIColor blackColor]; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"後退" style:UIBarButtonItemStyleDone target:self action:@selector(goback)]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"前進" style:UIBarButtonItemStyleDone target:self action:@selector(gofarward)]; } - (void)goback { if ([self.webView canGoBack]) { [self.webView goBack]; } } - (void)gofarward { if ([self.webView canGoForward]) { [self.webView goForward]; } } #pragma mark - WKScriptMessageHandler // 通過這個方法獲取 JS傳來的json字符串 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name isEqualToString:@"iosModel"]) { // 打印所傳過來的參數,只支持NSNumber, NSString, NSDate, NSArray, // NSDictionary, and NSNull類型 NSLog(@"JS傳來的json字符串 : %@", message.body); NSDictionary *jsDictionary = message.body; if ([jsDictionary[@"means"] isEqualToString:@"獲取系統圖片"]) { [self beginOpenPhoto]; } } } #pragma mark - KVO - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"loading"]) { NSLog(@"loading"); } else if ([keyPath isEqualToString:@"title"]) { self.title = self.webView.title; } else if ([keyPath isEqualToString:@"estimatedProgress"]) { NSLog(@"progress: %f", self.webView.estimatedProgress); self.progressView.progress = self.webView.estimatedProgress; } if (!self.webView.loading) { [UIView animateWithDuration:0.5 animations:^{ self.progressView.alpha = 0; }]; } } #pragma mark - WKNavigationDelegate // 請求開始前,會先調用此代理方法 // 與UIWebView的 // - (BOOL)webView:(UIWebView *)webView // shouldStartLoadWithRequest:(NSURLRequest *)request // navigationType:(UIWebViewNavigationType)navigationType; // 類型,在請求先判斷能不能跳轉(請求) - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction: (WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *hostname = navigationAction.request.URL.host.lowercaseString; if (navigationAction.navigationType == WKNavigationTypeLinkActivated && ![hostname containsString:@".lanou.com"]) { // 對於跨域,需要手動跳轉, 用系統浏覽器(Safari)打開 [[UIApplication sharedApplication] openURL:navigationAction.request.URL]; // 不允許web內跳轉 decisionHandler(WKNavigationActionPolicyCancel); } else { self.progressView.alpha = 1.0; decisionHandler(WKNavigationActionPolicyAllow); } } // 在響應完成時,會回調此方法 // 如果設置為不允許響應,web內容就不會傳過來 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { decisionHandler(WKNavigationResponsePolicyAllow); } // 開始導航跳轉時會回調 - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation { } // 接收到重定向時會回調 - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation { } // 導航失敗時會回調 - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { } // 頁面內容到達main frame時回調 - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation { } // 導航完成時,會回調(也就是頁面載入完成了) - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"66===%s", __FUNCTION__); // 禁用選中效果 [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil]; [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil]; } // 導航失敗時會回調 - (void)webView:(WKWebView *)webView didFailNavigation: (null_unspecified WKNavigation *)navigation withError:(NSError *)error { } /* 對於HTTPS的都會觸發此代理,如果不要求驗證,傳默認就行 如果需要證書驗證,與使用AFN進行HTTPS證書驗證是一樣的 */ - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge completionHandler: (void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler { completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); } // 9.0才能使用,web內容處理中斷時會觸發 /* - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { } */ #pragma mark - WKUIDelegate - (void)webViewDidClose:(WKWebView *)webView { } /* 在JS端調用alert函數時,會觸發此代理方法。JS端調用alert時所傳的數據可以通過message拿到 在原生得到結果後,需要回調JS,是通過completionHandler回調 */ - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler(); }]]; [self presentViewController:alert animated:YES completion:NULL]; NSLog(@"%@", message); } // JS端調用confirm函數時,會觸發此方法 // 通過message可以拿到JS端所傳的數據 // 在iOS端顯示原生alert得到YES/NO後 // 通過completionHandler回調給JS端 - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){ completionHandler(YES); }]]; [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { completionHandler(NO); }]]; [self presentViewController:alert animated:YES completion:NULL]; NSLog(@"%@", message); } // JS端調用prompt函數時,會觸發此方法 // 要求輸入一段文本 // 在原生輸入得到文本內容後,通過completionHandler回調給JS - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler { UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.textColor = [UIColor redColor]; }]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler([[alert.textFields lastObject] text]); }]]; [self presentViewController:alert animated:YES completion:NULL]; } // 獲取圖片 - (void)beginOpenPhoto { // 主隊列 異步打開相機 dispatch_async(dispatch_get_main_queue(), ^{ [self takePhoto]; }); } #pragma mark 取消選擇照片代理方法 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; } #pragma mark //打開本地照片 - (void) localPhoto { UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init]; imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; imagePicker.delegate = self; [self presentViewController:imagePicker animated:YES completion:nil]; } #pragma mark //打開相機拍照 - (void) takePhoto { UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *picker = [[UIImagePickerController alloc]init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType = sourceType; picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentViewController:picker animated:YES completion:nil]; } else { NSLog(@"模擬器中不能打開相機"); [self localPhoto]; } } // 選擇一張照片後進入這裡 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *type = [info objectForKey:UIImagePickerControllerMediaType]; // 當前選擇的類型是照片 if ([type isEqualToString:@"public.image"]) { // 獲取照片 getImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; NSLog(@"===Decoded image size: %@", NSStringFromCGSize(getImage.size)); // obtainImage 壓縮圖片 返回原尺寸 indextNumb = indextNumb == 1?2:1; NSString *nameStr = [NSString stringWithFormat:@"Varify%d.jpg",indextNumb]; [SaveImage_Util saveImage:getImage ImageName:nameStr back:^(NSString *imagePath) { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"圖片路徑:%@",imagePath); /** * 這裡是IOS 調 js 其中 setImageWithPath 就是js中的方法 setImageWithPath(),參數是字典 */ NSString *callJSString = [NSString stringWithFormat:@"%@({\"imagePath\":\"%@\",\"iosContent\":\"獲取圖片成功,把系統獲取的圖片路徑傳給js 讓html顯示\"})",@"setImageWithPath",imagePath]; [self.webView evaluateJavaScript:callJSString completionHandler:^(id resultObject, NSError * _Nullable error) { if (!error) { NSLog(@"OC調 JS成功"); } else { NSLog(@"OC調 JS 失敗"); } }]; }); }]; [picker dismissViewControllerAnimated:YES completion:nil]; } } @end
下面是圖片處理的 工具類
// SaveImage_Util.h // JS和iOS交互 // // Created by user on 16/10/14. // Copyright © 2016年 user. All rights reserved. // #import#import @interface SaveImage_Util : NSObject #pragma mark 保存圖片到document + (BOOL)saveImage:(UIImage *)saveImage ImageName:(NSString *)imageName back:(void(^)(NSString *imagePath))back; @end
// SaveImage_Util.m // JS和iOS交互 // // Created by user on 16/10/14. // Copyright © 2016年 user. All rights reserved. // #import "SaveImage_Util.h" @implementation SaveImage_Util #pragma mark 保存圖片到document + (BOOL)saveImage:(UIImage *)saveImage ImageName:(NSString *)imageName back:(void(^)(NSString *imagePath))back { NSString *path = [SaveImage_Util getImageDocumentFolderPath]; NSData *imageData = UIImagePNGRepresentation(saveImage); NSString *documentsDirectory = [NSString stringWithFormat:@"%@/", path]; // Now we get the full path to the file NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:imageName]; // and then we write it out NSFileManager *fileManager = [NSFileManager defaultManager]; //如果文件路徑存在的話 BOOL bRet = [fileManager fileExistsAtPath:imageFile]; if (bRet) { // NSLog(@"文件已存在"); if ([fileManager removeItemAtPath:imageFile error:nil]) { // NSLog(@"刪除文件成功"); if ([imageData writeToFile:imageFile atomically:YES]) { // NSLog(@"保存文件成功"); back(imageFile); } } else { } } else { if (![imageData writeToFile:imageFile atomically:NO]) { [fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil]; if ([imageData writeToFile:imageFile atomically:YES]) { back(imageFile); } } else { return YES; } } return NO; } #pragma mark 從文檔目錄下獲取Documents路徑 + (NSString *)getImageDocumentFolderPath { NSString *patchDocument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; return [NSString stringWithFormat:@"%@/Images", patchDocument]; } @end