withError:(NSError *)error{
NSLog(@"加载失败");
}
//收到服务器重定向请求后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
NSLog(@"服务器重定向");
}
//当main frame最后下载数据失败时,会回调
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
NSLog(@"返回内容发生错误");
}
//用于授权验证的API,与AFN、UIWebView的授权验证API是一样的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,nil);
}
//当web content处理完成时,会回调
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0)){
NSLog(@"WebContent完成");
}
View Code
这里放一个完整的WKWebView例子,仅供参考:
//初始化WKPreferences,并设置相关属性
WKPreferences *preference = [[WKPreferences alloc]init];
//初始化WKUserContentController,并设置相关属性
WKUserContentController *userController = [[WKUserContentController alloc]init];
// 添加在js中操作的对象名称,通过该对象来向web view发送消息
// JS 端可通过 window.webkit.messageHandlers..postMessage() 发送消息
// <script type="text/java script">
// function clickBtn(){
// var dict = {"name":"tom","age":"20"};
// window.webkit.messageHandlers.JSSendToOC.postMessage(dict);
// }
// </script>
[userController addScriptMessageHandler:self name:@"JSSendToOC"];
//初始化WKWebsiteDataStore,并设置相关属性
WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];
// 如果为webView设置了这个data Store,则不会有数据缓存被写入文件
// 当需要实现隐私浏览的时候,可使用这个
// WKWebsiteDataStore *dataStore = [WKWebsiteDataStore nonPersistentDataStore];
//配置信息
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init];
configuration.preferences = preference;
configuration.userContentController = userController;
configuration.websiteDataStore = dataStore;
self.iWKWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64) configuration:configuration];
self.iWKWebView.navigationDelegate = self;
self.iWKWebView.UIDelegate = self;
self.iWKWebView.allowsBackForwardNavigationGestures = YES;
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.iWKWebView loadRequest:request];
[self.view addSubview:self.iWKWebView];
再加一个知识点:WKWebView加载的时候添加一个自定义的进度条。
此时我们需要获取到webview加载的进度数值。
这里可以通过添加监听来获取。
[self.iWKWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
estimatedProgress是WKWebView的一个属性。
-(void)observeva lueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqualToString:@&