在
This Question中说,AFNetworking在后台自动处理cookies,但是在
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
解决方法
使用以下内容,这是保存和加载适用于我的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]; } }
希望有帮助!