iOS WKWebView 免登陆

简介:

就不复述官方对WKWebView的描述了,随便搜一下就有一大推。简单的说,WKWebView是iOS8之后推出的,与UIWebView作用相同,但是在加载速度、内存占用等方面都有显著提升。

常用的协议方法:

  • 开始加载网页的时候调用。
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { 
}
  • 服务器收到请求后,返回网页内容。
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
}

  • 页面加载完成,可以在该方法中通过webView.title设置导航条标题。
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}
  • 页面加载发生错误,可以获取错误信息,重新加载网页[webView reload]
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
  • 页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}

上面这几个方法都不是我在做免登陆时用到的主要方法,哈哈哈!

进入正题,网页中的免登陆(有点瑕疵)

需求:加载某个网页(例:),第一次加载需要登陆,退出网页后下次加载时避免二次登陆。

  • 第一步
    在创建WKWebView对象时,选择自定义配置加载网页时携带的cookie等(WKWebViewConfiguration)。如果本地存在上次登陆保留的cookie,那么直接将cookie配置到webView中,可以在加载后面的页面时自动携带cookie。如果本地没有,不好意思,登陆吧。
- (WKWebView *)webView {
    if (!_webView) {
        WKUserContentController* userContentController = [[WKUserContentController alloc] init];
        WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
        config.userContentController = userContentController;
        WKProcessPool *processPool = [[WKProcessPool alloc] init];
        config.processPool = processPool;
        
        WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[self cookieJavaScriptString] injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        [userContentController addUserScript:cookieScript];
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
    }
    return _webView;
}
  • 第二步
    获取本地cookie,cookie的本地持久化我是用网页的host作为键值的,保证需要同一个cookie的网页通过host获取对应cookie。注意从本地取出的不是cookie对象,而是取出它的内容,然后创建的cookie对象(直接本地存储cookie做不到)。这里NSHTTPCookieStorage我就不介绍了。
//配置config,获取cookieString
- (NSString *)cookieJavaScriptString {
    NSMutableString *cookieString = [[NSMutableString alloc] init];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDictionary *cookieDic = [userDefault objectForKey:self.urlHost];
    for (NSString *key in cookieDic) {
        NSHTTPCookie *cookie = [[NSHTTPCookie alloc] initWithProperties:[cookieDic objectForKey:key]];
        NSString *excuteJSString = [NSString stringWithFormat:@"document.cookie='%@=%@';", cookie.name, cookie.value];
        [cookieString appendString:excuteJSString];
    }
    //执行js
    return cookieString;
}
  • 第三步
    进行网页的跳转,在向服务器发送请求之前先判断请求是否携带了cookie(虽然第一步配置了cookie,以防万一还是要判断一下的),如果未携带cookie,取消跳转,手动添加cookie后跳转。
//发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    self.urlHost = navigationAction.request.URL.host;
    //判断是否存host
    if (self.urlHost) {
        if (!navigationAction.request.allHTTPHeaderFields[@"Cookie"]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            [self loadRequestWithString:navigationAction.request.URL];
        }else {
            decisionHandler(WKNavigationActionPolicyAllow);
        }
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

//手动添加cookie
- (void)loadRequestWithString:(NSURL *)url {    
    NSMutableString *cookieValue = [NSMutableString string];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDictionary *cookieDic = nil;
    if (self.urlHost) {
        cookieDic = [userDefault objectForKey:self.urlHost];
    }
    
    for (NSString *key in cookieDic) {
        NSHTTPCookie *cookie = [[NSHTTPCookie alloc] initWithProperties:[cookieDic objectForKey:key]];
        NSString *appendString = [NSString stringWithFormat:@"%@=%@;", cookie.name, cookie.value];
        [cookieValue appendString:appendString];
    }
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request addValue:cookieValue forHTTPHeaderField:@"Cookie"];
    [self.webView loadRequest:request];
}
  • 第四步
    保存cookie,第一次进入或cookie失效都是需要登录的,登录成功后我们就要将网页请求的cookie保存到本地,下次加载时直接拿出来用。
//接收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    //将获取的cookie本地化
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *cookieDic = [[NSMutableDictionary alloc] initWithDictionary:[userDefaults objectForKey:self.urlHost]];
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    for (NSHTTPCookie *cookie in cookies) {
        [cookieDic setObject:[cookie properties] forKey:cookie.name];
    }
    
    [userDefaults setObject:cookieDic forKey:self.urlHost];
    
    decisionHandler(WKNavigationActionPolicyAllow);
    
}

你可能感兴趣的:(iOS WKWebView 免登陆)