WKWebView在實際開發中的使用匯總

最近公司的項目中大量使用了webview加載H5,鑒于WKWebView的性能優于UIWebView,所以就選擇了WKWebView。WKWebView在使用的過程中,還是有很過內容值得我們去記錄和研究的,這里我就做了一下總結,跟大家分享一下。文章中的示例代碼可以到github中下載查看。

一、基本使用

WKWebView的基本使用網上也有很多,這里我就簡略的寫一下:
引入頭文件#import <WebKit/WebKit.h>

- (void)setupWebview{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.selectionGranularity = WKSelectionGranularityDynamic;
    config.allowsInlineMediaPlayback = YES;
    WKPreferences *preferences = [WKPreferences new];
    //是否支持JavaScript
    preferences.javaScriptEnabled = YES;
    //不通過用戶交互,是否可以打開窗口
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preferences;

    WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64) configuration:config];
    [self.view addSubview:webview];
    
    /* 加載服務器url的方法*/
    NSString *url = @"https://www.baidu.com";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [webview loadRequest:request];
    
    webview.navigationDelegate = self;
    webview.UIDelegate = self;
}

WKWebViewConfiguration和WKPreferences中有很多屬性可以對webview初始化進行設置,這里就不一一介紹了。

遵循的協議和實現的協議方法:

#pragma mark - WKNavigationDelegate
/* 頁面開始加載 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

}
/* 開始返回內容 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
/* 頁面加載完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}
/* 頁面加載失敗 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
/* 在發送請求之前,決定是否跳轉 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    //允許跳轉
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允許跳轉
    //decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到響應后,決定是否跳轉 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允許跳轉
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允許跳轉
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

下面介紹幾個開發中需要實現的小細節:

1、url中文處理
有時候我們加載的URL中可能會出現中文,需要我們手動進行轉碼,但是同時又要保證URL中的特殊字符保持不變,那么我們就可以使用下面的方法(方法放到了NSString中的分類中):

- (NSURL *)url{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8))];
#pragma clang diagnostic pop
}

2、獲取h5中的標題 3、添加進度條
獲取h5中的標題和添加進度條放到一起展示看起來更明朗一點,在初始化wenview時,添加兩個觀察者分別用來監聽webview 的estimatedProgresstitle屬性:

webview.navigationDelegate = self;
webview.UIDelegate = self;
    
[webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[webview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];

添加創建進度條,并添加進度條圖層屬性:

@property (nonatomic,weak) CALayer *progressLayer;
-(void)setupProgress{
    UIView *progress = [[UIView alloc]init];
    progress.frame = CGRectMake(0, 0, KScreenWidth, 3);
    progress.backgroundColor = [UIColor  clearColor];
    [self.view addSubview:progress];
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 3);
    layer.backgroundColor = [UIColor greenColor].CGColor;
    [progress.layer addSublayer:layer];
    self.progressLayer = layer;
}

實現觀察者的回調方法:

#pragma mark - KVO回饋
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressLayer.opacity = 1;
        if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
            return;
        }
        self.progressLayer.frame = CGRectMake(0, 0, KScreenWidth*[change[@"new"] floatValue], 3);
        if ([change[@"new"]floatValue] == 1.0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressLayer.opacity = 0;
                self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else if ([keyPath isEqualToString:@"title"]){
        self.title = change[@"new"];
    }
}

下面是實現的效果圖:


效果圖-1.gif

4、添加userAgent信息

有時候H5的伙伴需要我們為webview的請求添加userAgent,以用來識別操作系統等信息,但是如果每次用到webview都要添加一次的話會比較麻煩,下面介紹一個一勞永逸的方法。
在Appdelegate中添加一個WKWebview的屬性,啟動app時直接,為該屬性添加userAgent:

- (void)setUserAgent {
    _webView = [[WKWebView alloc] initWithFrame:CGRectZero];
    [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        if (error) { return; }
        NSString *userAgent = result;
        if (![userAgent containsString:@"/mobile-iOS"]) {
            userAgent = [userAgent stringByAppendingString:@"/mobile-iOS"];
            NSDictionary *dict = @{@"UserAgent": userAgent};
            [TKUserDefaults registerDefaults:dict];
        }
    }];
}

這樣一來,在app中創建的webview都會存在我們添加的userAgent的信息。

二、原生JS交互

(一)JS調用原生方法
在WKWebView中實現與JS的交互還需要實現另外一個代理方法:WKScriptMessageHandler

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message

messagenamebody屬性中我們可以獲取到與JS調取原生的方法名和所傳遞的參數。

打印一下如下圖所示:

效果圖-3.jpg

JS調用原生方法的代碼:

window.webkit.messageHandlers.takePicturesByNative.postMessage({
                    "picType": "0",
                    "picCount":"9",
                    "callBackName": "getImg"
                })
        }

注意:JS只能向原生傳遞一個參數,所以如果有多個參數需要傳遞,可以讓JS傳遞對象或者JSON字符串即可。

(二)原生調用JS方法

[webview evaluateJavaScript:“JS語句” completionHandler:^(id _Nullable data, NSError * _Nullable error) {
       
 }];

下面舉例說明:

實現H5通過原生方法調用相冊

首先,遵循代理:

<WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>

注冊方法名:

config.preferences = preferences;

WKUserContentController *user = [[WKUserContentController alloc]init];
[user addScriptMessageHandler:self name:@"takePicturesByNative"];
config.userContentController =user;

實現代理方法:

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"takePicturesByNative"]) {
       [self takePicturesByNative];
    }
}
- (void)takePicturesByNative{
    UIImagePickerController *vc = [[UIImagePickerController alloc] init];
    vc.delegate = self;
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSTimeInterval timeInterval = [[NSDate date]timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f",timeInterval];
    
    UIImage *image = [info  objectForKey:UIImagePickerControllerOriginalImage];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",timeString]];  //保存到本地
    [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
    NSString *str = [NSString stringWithFormat:@"%@",filePath];
    [picker dismissViewControllerAnimated:YES completion:^{
        // oc 調用js 并且傳遞圖片路徑參數
        [self.webview evaluateJavaScript:[NSString stringWithFormat:@"getImg('%@')",str] completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        }];

    }];
}

我們期望的效果是,點擊webview中打開相冊的按鈕,調用原生方法,展示相冊,選擇圖片,可以傳遞給JS,并展示在webview中。
但是運行程序發現:我們可以打開相冊,說明JS調用原生方法成功了,但是并不能在webview中展示出來,說明原生調用JS方法時,出現了問題。這是因為,在WKWebView中,H5在加載本地的資源(包括圖片、CSS文件、JS文件等等)時,默認被禁止了,所以根據我們傳遞給H5的圖片路徑,無法展示圖片。解決辦法:在傳遞給H5的圖片路徑中添加我們自己的請求頭,攔截H5加載資源的請求頭進行判斷,拿到路徑然后由我們來手動請求。

先為圖片路徑添加一個我們自己的請求頭:

NSString *str = [NSString stringWithFormat:@"myapp://%@",filePath];

然后創建一個新類繼承于NSURLProtocol

.h

#import <UIKit/UIKit.h>
@interface MyCustomURLProtocol : NSURLProtocol
@end

.m

@implementation MyCustomURLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest*)theRequest{
    if ([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] == NSOrderedSame) {
        return YES;
    }
    return NO;
}

+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)theRequest{
    return theRequest;
}

- (void)startLoading{
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[self.request URL]
                                                        MIMEType:@"image/png"
                                           expectedContentLength:-1
                                                textEncodingName:nil];
    NSString *imagePath = [self.request.URL.absoluteString componentsSeparatedByString:@"myapp://"].lastObject;
    NSData *data = [NSData dataWithContentsOfFile:imagePath];
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
}
- (void)stopLoading{
}
@end

在控制器中注冊MyCustomURLProtocol協議并添加對myapp協議的監聽:

 //注冊
    [NSURLProtocol registerClass:[MyCustomURLProtocol class]];
    //實現攔截功能
    Class cls = NSClassFromString(@"WKBrowsingContextController");
    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
    if ([(id)cls respondsToSelector:sel]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [(id)cls performSelector:sel withObject:@"myapp"];
#pragma clang diagnostic pop
    }

運行程序,效果如下:


效果圖-2.gif

不僅僅是加載本地的圖片,webview加載任何本地的資源都可以使用該方法,不過在使用過程中,大家一定要密切注意跨域問題會帶來的安全性問題。

結尾

關于WKWebView其實還有很多內容,接下來我還會繼續深入地去探究WKWebView的原理和使用。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容