iOS登录状态带入到webView

1.获取登录时的cookie并保存。

NSHTTPCookieStorage  *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];      for(NSHTTPCookie*cookie in [cookies cookies])

 {

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];// 保存

  }

2.取出cookie,并添加到webView的请求头。

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:HOST]]; // 这里的HOST是你web服务器的域名地址

for (NSHTTPCookie *cookie in cookies)

{

 // cookiesWithResponseHeaderFields方法,需要为URL设置一个cookie为NSDictionary类型的header,注意NSDictionary里面的forKey需要是@"Set-Cookie"

 NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:[NSDictionary dictionaryWithObject: [[NSString alloc] initWithFormat:@"%@=%@",[cookie name],[cookie value]] forKey:@"Set-Cookie"] forURL:[NSURL URLWithString:self.htmlUrl]];

// 通过setCookies方法,完成设置,这样只要一访问URL为HOST的网页时,会自动附带上设置好的header

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:[NSURL URLWithString:self.htmlUrl]mainDocumentURL:nil];

 }

你可能感兴趣的:(iOS登录状态带入到webView)