亲身经历的WKWebView中的相关需求处理(持续更新)

2018-03-18  本文已影响35人  杨闯

区分是否在当前页面进行跳转切换

如果要写一个类似浏览器相关的应用程序,需要判断网页是要直接跳转还是创建新标签(或新窗口)展现一个新的页面,可以做出以下处理

- (WKWebView *)webView:(WKWebView *)webView 
   createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration 
   forNavigationAction:(WKNavigationAction *)navigationAction
   windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
          //做创建新标签或新窗口的相关处理
    }
    return nil;
}

和HTML进行JavaScript操作

HTML调用原生方法
注册:
config.userContentController=WKUserContentController()
config.userContentController.add(self,name:"QsId")   

接收到响应:
 public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "QsId") {
              //可以通过message.body找到传递过来的数据
        }
}
原生调用JavaScript方法
let str = "init(\"aerie\")"//
self.webView .evaluateJavaScript(str) { (data, error) in
    if(error != nil){

     }else{

      }
}

多个webview界面中共享cookie

如果你写一个简单的浏览器功能,那么可能会涉及到多个webview的显示,但是如果在一个界面上登录成功,保持登录状态,那么在另外一个webview中也要同步登录状态,那么久要让两个webview之间共用WKProcessPool,示例代码如下:

AppDelegate *appDelegate = (AppDelegate *)[NSApplication sharedApplication].delegate;
WKWebViewConfiguration *tion = [[WKWebViewConfiguration alloc] init];
tion.userContentController = [[WKUserContentController alloc] init];
tion.processPool = appDelegate.sharedProcessPool;
self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:tion];

鉴别是需要加载数据还是要下载文件

因为有一些网页上要处理下载文件,那么怎么判断要显示的是展现的网页图片等,还是要下载app文件呢,在这里需要使用代理方法,下边代码就是通过鉴别是不是要下载的应用而处理是要下载还是进行跳转显示

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    NSArray *typeArray = [navigationResponse.response.MIMEType componentsSeparatedByString:@"/"];
    if ([typeArray count] > 1) {
        NSString *strType = [typeArray firstObject];
        if ([@"application" isEqualToString:strType]) {
            [[NSWorkspace sharedWorkspace] openURL:navigationResponse.response.URL];
            decisionHandler(WKNavigationResponsePolicyCancel);//不允许跳转
            return;
        }
    }
    decisionHandler(WKNavigationResponsePolicyAllow);//允许跳转
}
上一篇下一篇

猜你喜欢

热点阅读