WKWebView免登陆,配置cookie

·  阅读 930
  • 需求:纯webapp第一次登录记住账号密码,退出app,下次启动时候免登录

第一步:

  • 创建wkwebview对象时,选择自定义配置加载网页是携带cookie。如果本地存有上次登录保留的cookie,那么直接将cookie配置到wkwebview,可以在加载后面的页面是自动携带cookie,本地没有缓存cookie,则跳转登录页.

    • (WKWebView *)webView { if (_webView == nil) { WKUserContentController *userContrntController = [[WKUserContentController alloc] init]; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.userContentController = userContrntController; WKProcessPool *processpool = [[WKProcessPool alloc] init]; config.processPool = processpool;

          WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:[self cookieJavaScriptString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
          [userContrntController addUserScript:cookieScript];
        
          _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-kNavigationBarHeight) configuration:config];
          _webView.navigationDelegate = self;
          _webView.UIDelegate = self;
          _webView.allowsBackForwardNavigationGestures = YES;
      复制代码

      } return _webView; }

第二步:

  • 获取本地cookie,cookie本地持久化用网页urlHost作为键值,保证需要同一个cookie的网页通过urlHost获取对应cookie,从本地取出cookie的内容

    //配置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]; } return cookieString; }

第三步:

  • 在网页跳转之前,向服务器发送请求之前先判断是否携带cookie,如果没有携带cookie,取消跳转,手动添加cookie在跳

    //发送请求之前,决定是否跳转

    • (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(nonnull WKNavigationAction *)navigationAction decisionHandler:(nonnull void (^)(WKNavigationActionPolicy))decisionHandler { self.urlHost = navigationAction.request.URL.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:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler { //将获取的cookie本地化 NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; NSMutableDictionary *cookieDic = [[NSMutableDictionary alloc] initWithDictionary:[userDefault 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]; } [userDefault setObject:cookieDic forKey:self.urlHost]; decisionHandler(WKNavigationResponsePolicyAllow); }
  • 注意:我这里的slef.urlHost默认是请求h5的域名

补充:最近测试的时候发现这么方法有点bug,如果cookie进场丢失,程序先是进入一个空白页面,时间很短暂,难以察觉,所以返回的时候会出现空白页,而且有时候一直返回不了,一直停留在空白页上。

        我的解决方法是在

-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler
复制代码

这个方法里添加一个判断操作,如果是返回的时候直接

decisionHandler(WKNavigationResponsePolicyAllow);
复制代码

所以要监听返回按钮的操作事件

分类:
iOS
标签:
收藏成功!
已添加到「」, 点击更改