在:This Question,据说AFNetworking
会在后台自动处理Cookie,但在Previous问题中我问过,我无法在服务器上保持会话当我登录时在php中制作。一旦我关闭(停止在Xcode中调试)应用程序并回到会话中就消失了。答案是坚持这样的cookie来解决问题:
NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"User"];
if ([cookiesData length] > 0) {
for (NSHTTPCookie *cookie in [NSKeyedUnarchiver cookiesData]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
当我尝试做这样的事情时,这给了我一个应用程序崩溃。当我登录时,我像这样设置NSUserDefault:
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"User"];
//Then synthesize
这是错误的使用方法吗? NSHTTPCookieStorage甚至是我的问题吗?感谢。
答案 0 :(得分:37)
使用以下命令,这是保存和加载适合我的Cookie的正确方法:
- (void)saveCookies{
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: cookiesData forKey: @"sessionCookies"];
[defaults synchronize];
}
- (void)loadCookies{
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in cookies){
[cookieStorage setCookie: cookie];
}
}
希望它有所帮助!