iOS開發(fā):WKWebView的使用(設(shè)置cookie咆耿、不受信任的HTTPS德谅、返回關(guān)閉按鈕)

效果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è)問題欢搜;

最后附上Demo地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末询微,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子狂巢,更是在濱河造成了極大的恐慌,老刑警劉巖书聚,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件唧领,死亡現(xiàn)場離奇詭異,居然都是意外死亡雌续,警方通過查閱死者的電腦和手機(jī)斩个,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來驯杜,“玉大人受啥,你說我怎么就攤上這事「胄模” “怎么了滚局?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長顽频。 經(jīng)常有香客問我藤肢,道長,這世上最難降的妖魔是什么糯景? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任嘁圈,我火速辦了婚禮,結(jié)果婚禮上蟀淮,老公的妹妹穿的比我還像新娘最住。我一直安慰自己,他們只是感情好怠惶,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布涨缚。 她就那樣靜靜地躺著,像睡著了一般甚疟。 火紅的嫁衣襯著肌膚如雪仗岖。 梳的紋絲不亂的頭發(fā)上逃延,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天,我揣著相機(jī)與錄音轧拄,去河邊找鬼揽祥。 笑死,一個(gè)胖子當(dāng)著我的面吹牛檩电,可吹牛的內(nèi)容都是我干的拄丰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼俐末,長吁一口氣:“原來是場噩夢啊……” “哼料按!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起卓箫,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤载矿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后烹卒,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體闷盔,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年旅急,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了逢勾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡藐吮,死狀恐怖溺拱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情谣辞,我是刑警寧澤迫摔,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站泥从,受9級(jí)特大地震影響攒菠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜歉闰,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一辖众、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧和敬,春花似錦凹炸、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春变骡,著一層夾襖步出監(jiān)牢的瞬間离赫,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來泰國打工塌碌, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留渊胸,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓台妆,卻偏偏與公主長得像翎猛,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子接剩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容