效果GIF.gif
之前也是使用UIWebView
,但是近期使用時(shí)碰到了問題萨螺,所以就想著更換成WKWebView
窄做。都知道WKWebView
是在iOS8之后蘋果推出的愧驱,也有很多大牛做了他和UIWebView
的對(duì)比,此處小弟就在敘述了椭盏,可以參考文章一组砚、文章二,我也是取各家之所長掏颊,以及在使用過程中遇到的問題糟红,寫下這篇文章,僅供參考乌叶!
創(chuàng)建DKSWebController
繼承自UIViewController
盆偿,頭文件如下:
#import <WebKit/WebKit.h>
@interface DKSWebController ()<WKNavigationDelegate, WKUIDelegate>
@property (nonatomic, strong) WKWebView *webView;
//返回按鈕
@property (nonatomic, strong) UIBarButtonItem *backItem;
//關(guān)閉按鈕
@property (nonatomic, strong) UIBarButtonItem *closeItem;
//進(jìn)度條
@property (nonatomic, strong) UIView *progressView;
@property (weak, nonatomic) CALayer *progresslayer;
@end
具體實(shí)現(xiàn)如下:代碼有點(diǎn)多,可以下載demo看看
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self addLeftButton]; //添加返回按鈕
}
#pragma mark ====== 加載HTML ======
- (void)loadHtmlStr:(NSString *)htmlStr {
NSURL *url = [NSURL URLWithString:htmlStr];
//不需要cookie的話准浴,此處只是簡單打開H5頁面
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}
#pragma mark ====== 加載進(jìn)度條 ======
- (void)addProgressView {
//添加進(jìn)度條(如果沒有需要事扭,可以注釋掉)
CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, navigationBarBounds.size.height, CGRectGetWidth(self.view.frame), 1)];
progress.backgroundColor = [UIColor clearColor];
[self.navigationController.navigationBar addSubview:progress];
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(0, 0, 0, 1);
layer.backgroundColor = [UIColor blueColor].CGColor;
[progress.layer addSublayer:layer];
self.progresslayer = layer;
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}
//kvo 監(jiān)聽進(jìn)度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progresslayer.opacity = 1;
self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[NSKeyValueChangeNewKey] floatValue], 1);
if ([change[NSKeyValueChangeNewKey] floatValue] == 1) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.opacity = 0;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progresslayer.frame = CGRectMake(0, 0, 0, 1);
});
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark ====== 添加進(jìn)度條 ======
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self addProgressView]; //添加進(jìn)度條
}
#pragma mark ====== 移除進(jìn)度條 ======
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//移除progressView,否則將會(huì)顯示在其他的導(dǎo)航欄上面
[self.progressView removeFromSuperview];
}
#pragma mark ====== WKWebViewDelegate ======
// 頁面開始加載時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}
// 當(dāng)內(nèi)容開始返回時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
}
// 頁面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//設(shè)置webview的title
self.title = webView.title;
}
// 頁面加載失敗時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"網(wǎng)絡(luò)不給力");
}
// 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
}
// 在收到響應(yīng)后乐横,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//允許跳轉(zhuǎn)
decisionHandler(WKNavigationResponsePolicyAllow);
//不允許跳轉(zhuǎn)
//decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在發(fā)送請(qǐng)求之前求橄,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//如果是跳轉(zhuǎn)一個(gè)新頁面
if (navigationAction.targetFrame == nil) {
[webView loadRequest:navigationAction.request];
}
decisionHandler(WKNavigationActionPolicyAllow);
}
#pragma mark - WKUIDelegate
// 創(chuàng)建一個(gè)新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
return [[WKWebView alloc]init];
}
// 輸入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
completionHandler(@"http");
}
// 確認(rèn)框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
completionHandler();
}
#pragma mark - 添加關(guān)閉按鈕
- (void)addLeftButton {
self.navigationItem.leftBarButtonItem = self.backItem;
}
//點(diǎn)擊返回的方法
- (void)backNative {
//判斷是否有上一層H5頁面
if ([self.webView canGoBack]) {
//如果有則返回
[self.webView goBack];
//同時(shí)設(shè)置返回按鈕和關(guān)閉按鈕為導(dǎo)航欄左邊的按鈕
self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
} else {
[self closeNative];
}
}
//關(guān)閉H5頁面,直接回到原生頁面
- (void)closeNative {
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark ====== init ======
- (WKWebView *)webView {
if (!_webView) {
_webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
[self.view addSubview:_webView];
}
return _webView;
}
- (UIBarButtonItem *)backItem {
if (!_backItem) {
_backItem = [[UIBarButtonItem alloc] init];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//這是一張“<”的圖片葡公,可以讓美工給切一張
UIImage *image = [UIImage imageNamed:@"sy_back"];
[btn setImage:image forState:UIControlStateNormal];
[btn setTitle:@"返回" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
[btn.titleLabel setFont:[UIFont systemFontOfSize:17]];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//字體的多少為btn的大小
[btn sizeToFit];
//左對(duì)齊
btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//讓返回按鈕內(nèi)容繼續(xù)向左邊偏移15罐农,如果不設(shè)置的話,就會(huì)發(fā)現(xiàn)返回按鈕離屏幕的左邊的距離有點(diǎn)兒大匾南,不美觀
btn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
btn.frame = CGRectMake(0, 0, 40, 40);
_backItem.customView = btn;
}
return _backItem;
}
- (UIBarButtonItem *)closeItem {
if (!_closeItem) {
_closeItem = [[UIBarButtonItem alloc] initWithTitle:@"關(guān)閉" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
_closeItem.tintColor = [UIColor blackColor];
}
return _closeItem;
}
#pragma mark - 移除進(jìn)度條的監(jiān)聽
- (void)dealloc {
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
@end
以上就是WKWebView的使用方法啃匿;
如果在使用時(shí)加載不受信任的HTTPS的話,需要實(shí)現(xiàn)代理方法如下:
//此方法在iOS8上面不執(zhí)行蛆楞,也就是iOS8目前不能加載不受信任的HTTPS(我目前知道的)
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
}
}
但是此代理方法在iOS8上面并不執(zhí)行溯乒,如果是自建證書,加載不受信任的HTTPS的話豹爹,此時(shí)在iOS8上面會(huì)顯示白屏裆悄,到目前為止并沒有找到解決方法。也有朋友提出解決方案臂聋,說使用正規(guī)的證書就行了光稼,我的內(nèi)心是抗拒的??。如果你有好的解決辦法孩等,一定要留言告知一聲艾君,萬分感謝!
加載H5時(shí)需要cookie肄方,使用AJAX進(jìn)行新的請(qǐng)求時(shí)需要cookie冰垄,也就是在跳轉(zhuǎn)新的H5時(shí)也需要cookie的話,設(shè)置方法如下:
//在開始加載webview時(shí)就不能用上面的方法了
- (void)loadHtmlStr:(NSString *)htmlStr {
NSURL *url = [NSURL URLWithString:htmlStr];
//如果需要設(shè)置cookie驗(yàn)證的話权她,使用此段代碼
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:[self readCurrentCookieWithDomain] forHTTPHeaderField:@"Cookie"];
[self.webView loadRequest:request];
}
#pragma mark ====== 設(shè)置cookie ======
- (NSString *)readCurrentCookieWithDomain {
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSMutableString *cookieString = [[NSMutableString alloc] init];
for (NSHTTPCookie *cookie in [cookieJar cookies]) {
[cookieString appendFormat:@"%@=%@;", cookie.name, cookie.value];
}
//刪除最后一個(gè)“虹茶;”
[cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
return cookieString;
}
// 在發(fā)送請(qǐng)求之前逝薪,決定是否跳轉(zhuǎn)并設(shè)置cookie,帶入到新的請(qǐng)求
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//此處是在頁面跳轉(zhuǎn)時(shí)蝴罪,防止cookie丟失做的處理
WKNavigationActionPolicy policy = WKNavigationActionPolicyAllow;
NSURL *url = navigationAction.request.URL;
//此處的m.duks.com是自己公司的域名
if ([url.host isEqualToString:@"m.duks.com"]) {
NSDictionary *headFields = navigationAction.request.allHTTPHeaderFields;
NSString *cookie = headFields[@"Cookie"];
if (cookie == nil) {
//在跳轉(zhuǎn)新的web頁面時(shí)董济,把cookie傳過去
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:navigationAction.request.URL];
[request setValue:[self readCurrentCookieWithDomain] forHTTPHeaderField:@"Cookie"];
[webView loadRequest:request];
policy = WKNavigationActionPolicyCancel;
}
}
//如果是跳轉(zhuǎn)一個(gè)新頁面
if (navigationAction.targetFrame == nil) {
[webView loadRequest:navigationAction.request];
}
decisionHandler(WKNavigationActionPolicyAllow);
}
如果是比較老的項(xiàng)目使用WKWebView,并且使用過程中用到WebViewJavascriptBridge要门,有可能會(huì)引起崩潰
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//如果是跳轉(zhuǎn)一個(gè)新頁面
if (navigationAction.targetFrame == nil) {
[webView loadRequest:navigationAction.request];
}
//這一行崩潰
decisionHandler(WKNavigationActionPolicyAllow);
}
此時(shí)我建議更新這個(gè)三方庫虏肾,原因是這個(gè)方法被多次調(diào)用,這個(gè)庫的作者也更新了這個(gè)問題欢搜;