封装的工具类:
+(NSHTTPCookie*)cookieMakerWithName:(NSString*)name value:(NSString*)value Domain:(NSString*)domain path:(NSString*)path{
if ([name isEqualToString:EMPTYSTRING] || [value isEqualToString:EMPTYSTRING]) {
return nil;
}
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:name forKey:NSHTTPCookieName];
[cookieProperties setObject:value forKey:NSHTTPCookieValue];
[cookieProperties setObject:domain forKey:NSHTTPCookieDomain];
[cookieProperties setObject:domain forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:path forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"1" forKey:NSHTTPCookieVersion];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
return cookie;
}
+(NSArray*)cookieMakerWithValueDic:(NSDictionary*)valueDic Domain:(NSString*)domain path:(NSString*)path{
if ([valueDic isEqual:@{}]) {
return nil;
}
NSMutableArray *cookieArray = [NSMutableArray array];
for (NSString* key in valueDic) {
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:key forKey:NSHTTPCookieName];
[cookieProperties setObject:[valueDic objectForKey:key] forKey:NSHTTPCookieValue];
[cookieProperties setObject:domain forKey:NSHTTPCookieDomain];
[cookieProperties setObject:domain forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:path forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"1" forKey:NSHTTPCookieVersion];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[cookieArray addObject:cookie];
}
return cookieArray;
}
工具的调用:
#pragma mark - setCookie
- (void)setCookie {
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSDictionary *cookieValueDic = [NSDictionary dictionaryWithObjectsAndKeys:
@"value1",@"key1",
@"value2",@"key2",
@"value3",@"key3",
nil];
NSArray *cookieArray = [VATool cookieMakerWithValueDic:cookieValueDic Domain:self.urlHost path:@"/"];
for (NSHTTPCookie *cookie in cookieArray) {
[cookieStorage setCookie:cookie];
}
[self.webView reload];
}