我想在加载webview URL之前在现有cookie中添加三个额外的值,如firstname,lastname和title,这样用户就不必再次在webview中登录..是否可以在现有cookie中添加额外的值目标C?
答案 0 :(得分:1)
是的,您可以使用NSHTTPCookie
和NSHTTPCookieStorage
1)创建字典以设置cookie的属性(下面是cookie的几个属性):
NSMutableDictionary *dictCookieID = [NSMutableDictionary dictionary];
[dictCookieID setObject:value forKey:NSHTTPCookieName];
[dictCookieID setObject:value forKey:NSHTTPCookieValue];
[dictCookieID setObject:value forKey:NSHTTPCookieDomain];
[dictCookieID setObject:value forKey:NSHTTPCookiePath];
[dictCookieID setObject:value forKey:NSHTTPCookieVersion];
2)创建 NSHTTPCookie
NSHTTPCookie *cookieID = [NSHTTPCookie dictCookieID];
3)存储cookie:
NSArray *cookies = [NSArray arrayWithObjects: cookieID,nil]; // You can add multiple cookies in this array
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieID];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
4)将网址加载到webview:
NSString* url = URL_NAME;
NSURL* nsUrl = [NSURL URLWithString:url];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:];
[request setHTTPShouldHandleCookies:YES];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[(NSMutableURLRequest *)request setAllHTTPHeaderFields:headers];
[webView loadRequest:request];
答案 1 :(得分:1)
使用NSURLSession
,您可以在NSHTTPCookieStorage
中设置Cookie。但是,cookie只是您可以设置的标题字段。