美文网首页
WKWebView实现加载网页

WKWebView实现加载网页

作者: llq_31da | 来源:发表于2018-03-28 17:30 被阅读0次

    1.首先要导入WebKit框架;2.通过- (instancetype)initWithFrame:(CGRect)frame方法创建WKWebView;3.设置对应代理navigationDelegate和UIDelegate;4.实现对应代理方法。5.通过WKWebView的configuration属性的userContentController调用- (void)addScriptMessageHandler:(id)scriptMessageHandler name:(NSString *)name方法来添加JS调用OC的方法;

    WKNavigationDelegate代理方法:常用的处理跳转加载操作的代理                                                                         在发送请求之前,决定是否跳转   - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{}       

     页面开始加载时调用 - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation  

    在收到响应后,决定是否跳转:此方法必须设置对应的回调函数,否则会崩溃      - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler                      

    当内容开始返回时调用- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation     

    页面加载完成之后调用- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation

    页面加载失败时调用- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error

    WKUIDelegate代理方法:常用的主要处理JS脚本,确认框,警告框等

     创建一个新的WebView- (WKWebView*)webView:(WKWebView*)webView createWebViewWithConfiguration:(WKWebViewConfiguration*)configuration forNavigationAction:(WKNavigationAction*)navigationAction windowFeatures:(WKWindowFeatures*)windowFeatures{return[[WKWebViewalloc]init];}

     输入框- (void)webView:(WKWebView*)webView runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt defaultText:(nullableNSString*)defaultText initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(NSString* __nullableresult))completionHandler{ completionHandler(@"http");}

     确认框- (void)webView:(WKWebView*)webView runJavaScriptConfirmPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(BOOLresult))completionHandler{ completionHandler(YES);}

     警告框- (void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(void))completionHandler{NSLog(@"%@",message); completionHandler();}

    碰到问题:WKWebView需要手动添加cookie;第一次请求页面添加cookie可以在decidePolicyForNavigationAction代理方法中给请求头加上cookie;新页面中增加cookie需要在didFinishNavigation方法中给H5页面中增加对应cookie

    目前只是简单认识了WKWebView;更深的问题还需要继续研究。。。

    相关文章

      网友评论

          本文标题:WKWebView实现加载网页

          本文链接:https://www.haomeiwen.com/subject/hqrycftx.html