iOS UIWebView重定向Cookie

时间:2022-03-10 08:03:35
     // 1. 取出当前的cookies
NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
// 2. 取出需要同步到的地址url
BESTHttpItem *httpItem = [BESTHttpHelper sharedHelper].curHttpItem;
NSString *url = [NSString stringWithFormat:@"%@/#/login", httpItem.frontend_addr]; // 3. 遍历cookies
for (NSHTTPCookie *cookie in cookies) {
// 4. 设置header的cookie信息
NSString *cookieString = [[NSString alloc] initWithFormat:@"%@=%@",[cookie name],[cookie value]];
NSDictionary *setCookieDic = [NSDictionary dictionaryWithObject:cookieString forKey:@"Set-Cookie"];
NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:setCookieDic forURL:[NSURL URLWithString:url]]; // 5. 通过setCookies方法,完成设置,这样只要一访问URL为HOST的网页时,会自动附带上设置好的header
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie
forURL:[NSURL URLWithString:url]
mainDocumentURL:nil];
}