标签:only form share documents tor cookie request storage web
NSURLRequest 会记录访问站点设置的cookie信息,且保存下来,在下次访问改站点的时候会自动带上这个cookie去请求。
查看cookie:
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (NSHTTPCookie *cookie in [cookieJar cookies]) { NSLog(@"%@", cookie); }
清空cookie:
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (id obj in [cookieJar cookies]) { [cookieJar deleteCookie:obj]; }
设置cookie:
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
每个应用都有自己的沙盒,A应用的cookie是不能被B应用访问的。
WKWebView Cookie 问题在于 WKWebView 发起的请求不会自动带上存储于 NSHTTPCookieStorage 容器中的 Cookie。
实践发现 WKWebView 实例其实也会将 Cookie 存储于 NSHTTPCookieStorage 中,但存储时机有延迟
UIWebview的cookie处理:
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
WKWebview的cookie处理方式:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://my.domain.com"]]; NSDictionary *headFields = request.allHTTPHeaderFields; NSString *cookie = headFields[@"user"]; if (cookie == nil) { [request addValue:[NSString stringWithFormat:@"user=%@", @"userValue"] forHTTPHeaderField:@"Cookie"]; } [self.wkwebView loadRequest:request];
ajax
请求的话,那 cookie 又要重新处理了,这个处理需要在 WKWebView 的 WKWebViewConfiguration 中进行配置。WKUserContentController *userContentController = WKUserContentController.new; NSString *cookieSource = [NSString stringWithFormat:@"document.cookie = ‘user=%@‘;", @"userValue"]; WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; [userContentController addUserScript:cookieScript]; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; config.userContentController = userContentController;
标签:only form share documents tor cookie request storage web
原文地址:https://www.cnblogs.com/diyigechengxu/p/12121132.html