在
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
这是错误的使用方法吗? NShttpcookiestorage甚至我的问题?谢谢.
解决方法
使用以下内容,这是保存和加载适用于我的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]; } }
希望有帮助!