登录成功后
NSUserDefaults * defaults =[NSUserDefaults standardUserDefaults];
NSArray * allCookies =[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie * cookie in allCookies) {
if ([cookie.name isEqualToString:@"PHPSESSID"]) {
NSMutableDictionary *cookieDictonary =[NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:@"MyProjectCookie"]];
[cookieDictonary setValue:cookie.properties forKey:@"cookieDict"];
[defaults setObject:cookieDictonary forKey:@"MyProjectCookie"];
[defaults synchronize];
break;
}
}
AF框架中
//设置请求头
if (![requestURLString containsString:BP_LOGIN]||![requestURLString containsString:BP_REGISTERED]) {
NSLog(@"不是登录接口%@",[[[NSUserDefaults standardUserDefaults] objectForKey:@"MyProjectCookie"] valueForKey:@"cookieDict"]);
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"MyProjectCookie"] valueForKey:@"cookieDict"]!=nil&&[GLUserModel shareInstance].loginY) {
NSHTTPCookie *cookie =[NSHTTPCookie cookieWithProperties:[[[NSUserDefaults standardUserDefaults] objectForKey:@"MyProjectCookie"] valueForKey:@"cookieDict"]];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
手动创建cookie
// 创建cookie属性字典
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"username" forKey:NSHTTPCookieName]; // 手动设置cookie的属性
[cookieProperties setObject:@"rainbird" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
// 通过NSHTTPCookie的cookieWithProperties方法,将属性字典传入进行初始化,对象返回的是一个NSHTTPCookie对象,创建完成后进行下一步操作:
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
// 将手动创建返回的NSHTTPCookie对象添加到NSHTTPCookieStorage中,在iOS中使用[NSHTTPCookie]
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
(http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookie_Class/Reference/Reference.html)类封装一条cookie,通过NSHTTPCookie的方法读取到cookie的通用属性。在此声明一点:如果你的request里面明确不使用cookie,那么要讲cookie的([HTTPShouldHandleCookies]
(http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURLRequest/HTTPShouldHandleCookies)设为NO),否则URL loading system会自动为NSURLRequest发送合适的存储cookie。
//文章来源http://jinqianchina.github.io/2016/01/07/Cookie%E6%9C%BA%E5%88%B6%E4%BB%A5%E5%8F%8Acookie%E5%9C%A8iOS%E4%B8%AD%E4%BD%BF%E7%94%A8%E4%BB%8B%E7%BB%8D/
http://www.jianshu.com/p/65094611980c
网友评论