iOS8以后核畴,蘋果推出了新框架Webkit含蓉,提供了替換UIWebView的組件WKWebView。其優(yōu)點(diǎn)速度更快项郊,占用內(nèi)存更少馅扣,簡(jiǎn)而言之,WKWebView是App內(nèi)部加載網(wǎng)頁(yè)的最佳選擇着降。
WKNavigationDelegate代理方法
#pragma mark -----WKNavigationDelegate---------
// 頁(yè)面開始加載時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"頁(yè)面開始加載時(shí)調(diào)用");
}
// 當(dāng)內(nèi)容開始返回時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSLog(@"當(dāng)內(nèi)容開始返回時(shí)調(diào)用");
}
// 頁(yè)面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"頁(yè)面加載完成之后調(diào)用");
}
// 頁(yè)面加載失敗時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"頁(yè)面加載失敗時(shí)調(diào)用");
}
// 頁(yè)面導(dǎo)航錯(cuò)誤時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error {
NSLog(@"頁(yè)面導(dǎo)航錯(cuò)誤時(shí)調(diào)用");
}
//頁(yè)面終結(jié)時(shí)調(diào)用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
NSLog(@"頁(yè)面終結(jié)時(shí)調(diào)用");
}
// 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用");
}
// 在收到響應(yīng)后差油,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSLog(@"在收到響應(yīng)后,決定是否跳轉(zhuǎn)");
decisionHandler(WKNavigationResponsePolicyAllow);
}
// 在發(fā)送請(qǐng)求之前任洞,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSLog(@"在發(fā)送請(qǐng)求之前蓄喇,決定是否跳轉(zhuǎn)");
decisionHandler(WKNavigationActionPolicyAllow);
}
//證書驗(yàn)證處理
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
NSLog(@"證書驗(yàn)證處理");
// 判斷服務(wù)器采用的驗(yàn)證方法
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
// 如果沒有錯(cuò)誤的情況下 創(chuàng)建一個(gè)憑證,并使用證書
if (challenge.previousFailureCount == 0) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}else {
//驗(yàn)證失敗交掏,取消本次驗(yàn)證
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
WKUIDelegate代理方法
#pragma mark ----WKUIDelegate協(xié)議----
/**
* web界面中有彈出警告框時(shí)調(diào)用
*
* @param webView 實(shí)現(xiàn)該代理的webview
* @param message 警告框中的內(nèi)容
* @param frame 主窗口
* @param completionHandler 警告框消失調(diào)用
*/
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(void))completionHandler {
// js 里面的alert實(shí)現(xiàn)妆偏,如果不實(shí)現(xiàn),網(wǎng)頁(yè)的alert函數(shù)無效
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
completionHandler();
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
/**
web界面中有彈出選擇框
@param webView 實(shí)現(xiàn)該代理的webview
@param message 警告框中的內(nèi)容
@param frame 主窗口
@param completionHandler 警告框消失調(diào)用 得到選擇結(jié)果
*/
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
// js 里面的alert實(shí)現(xiàn)盅弛,如果不實(shí)現(xiàn)钱骂,網(wǎng)頁(yè)的alert函數(shù)無效 ,
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
completionHandler(YES);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action){
completionHandler(NO);
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
/**
web界面中有彈出輸入框
@param webView 實(shí)現(xiàn)該代理的webview
@param prompt 輸入框的提示內(nèi)容
@param defaultText 默認(rèn)的填寫內(nèi)容
@param frame 主窗口
@param completionHandler 警告框消失調(diào)用 得到輸入內(nèi)容
*/
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(NSString * _Nullable))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor blackColor];
textField.text = defaultText;
}];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler([[alert.textFields lastObject] text]);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
添加進(jìn)度條UIProgressView
需要通過KVO監(jiān)聽進(jìn)行實(shí)現(xiàn),初始化頁(yè)面時(shí)添加監(jiān)聽事件
//初始化頁(yè)面時(shí)添加監(jiān)聽事件
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
// 計(jì)算wkWebView進(jìn)度條
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
NSLog(@"estimatedProgress");
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (newprogress == 1) {
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
}else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
}else if ([keyPath isEqualToString:@"title"]) {
NSLog(@"title");
self.title = self.webView.title;
}else if ([keyPath isEqualToString:@"loading"]) {
NSLog(@"loading");
}
}
頁(yè)面代碼示例 下載Demo
#import <WebViewController.h>
#import <WebKit/WebKit.h>
@interface WebViewController ()<WKNavigationDelegate, WKUIDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (strong, nonatomic) UIProgressView *progressView;
@end
@implementation WebViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.requestUrlStr]]];
// Do any additional setup after loading the view.
}
#pragma mark -----WKNavigationDelegate---------
// 頁(yè)面開始加載時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"頁(yè)面開始加載時(shí)調(diào)用");
}
// 當(dāng)內(nèi)容開始返回時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSLog(@"當(dāng)內(nèi)容開始返回時(shí)調(diào)用");
}
// 頁(yè)面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"頁(yè)面加載完成之后調(diào)用");
}
// 頁(yè)面加載失敗時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"頁(yè)面加載失敗時(shí)調(diào)用");
}
// 頁(yè)面導(dǎo)航錯(cuò)誤時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error {
NSLog(@"頁(yè)面導(dǎo)航錯(cuò)誤時(shí)調(diào)用");
}
//頁(yè)面終結(jié)時(shí)調(diào)用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
NSLog(@"頁(yè)面終結(jié)時(shí)調(diào)用");
}
// 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用");
}
//證書驗(yàn)證處理 基本上無需添加此代理方法
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
NSLog(@"證書驗(yàn)證處理");
// 判斷服務(wù)器采用的驗(yàn)證方法
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
// 如果沒有錯(cuò)誤的情況下 創(chuàng)建一個(gè)憑證挪鹏,并使用證書
if (challenge.previousFailureCount == 0) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}else {
//驗(yàn)證失敗见秽,取消本次驗(yàn)證
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
}
// 在收到響應(yīng)后,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSLog(@"在收到響應(yīng)后讨盒,決定是否跳轉(zhuǎn)");
decisionHandler(WKNavigationResponsePolicyAllow);
}
// 在發(fā)送請(qǐng)求之前解取,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSLog(@"在發(fā)送請(qǐng)求之前,決定是否跳轉(zhuǎn)");
decisionHandler(WKNavigationActionPolicyAllow);
}
// 計(jì)算wkWebView進(jìn)度條
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
NSLog(@"estimatedProgress");
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (newprogress == 1) {
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
}else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
}else if ([keyPath isEqualToString:@"title"]) {
NSLog(@"title");
self.title = self.webView.title;
}else if ([keyPath isEqualToString:@"loading"]) {
NSLog(@"loading");
}
}
#pragma mark ----WKUIDelegate協(xié)議----
/**
* web界面中有彈出警告框時(shí)調(diào)用
*
* @param webView 實(shí)現(xiàn)該代理的webview
* @param message 警告框中的內(nèi)容
* @param frame 主窗口
* @param completionHandler 警告框消失調(diào)用
*/
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(void))completionHandler {
// js 里面的alert實(shí)現(xiàn)返顺,如果不實(shí)現(xiàn)禀苦,網(wǎng)頁(yè)的alert函數(shù)無效
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
completionHandler();
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
/**
web界面中有彈出選擇框
@param webView 實(shí)現(xiàn)該代理的webview
@param message 警告框中的內(nèi)容
@param frame 主窗口
@param completionHandler 警告框消失調(diào)用 得到選擇結(jié)果
*/
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
// js 里面的alert實(shí)現(xiàn),如果不實(shí)現(xiàn)遂鹊,網(wǎng)頁(yè)的alert函數(shù)無效 ,
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
message:message
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"確定"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
completionHandler(YES);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action){
completionHandler(NO);
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
/**
web界面中有彈出輸入框
@param webView 實(shí)現(xiàn)該代理的webview
@param prompt 輸入框的提示內(nèi)容
@param defaultText 默認(rèn)的填寫內(nèi)容
@param frame 主窗口
@param completionHandler 警告框消失調(diào)用 得到輸入內(nèi)容
*/
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(NSString * _Nullable))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor blackColor];
textField.text = defaultText;
}];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler([[alert.textFields lastObject] text]);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
// 記得取消監(jiān)聽
- (void)dealloc {
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
[self.webView removeObserver:self forKeyPath:@"loading"];//移除kvo
[self.webView removeObserver:self forKeyPath:@"title"];
}
/**
清理緩存
*/
- (void)clearWbCache {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
}
- (WKWebView *)webView {
if (!_webView) {
_webView = [[WKWebView alloc] initWithFrame:self.view.frame];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
[self.view insertSubview:_webView belowSubview:self.progressView];
}
return _webView;
}
- (UIProgressView *)progressView {
if (!_progressView) {
_progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 0)];
self.progressView.tintColor = [UIColor orangeColor];
self.progressView.trackTintColor = [UIColor clearColor];
[self.view addSubview:self.progressView];
}
return _progressView;
}