问题描述
在:据说 AFNetworking
照顾Cookie在后台自动生成,但在我问过的问题中,我无法在服务器上保留会话当我登录时在php中制作。一旦我关闭(停止在Xcode中调试)应用程序并在会话中回去了。答案是坚持这样的cookie来解决问题:
In: This Question it is said AFNetworking
takes care of cookies automatically in the background, but in a Previous question I asked, I was having trouble keeping the session on the server that was made in php when I logged in. Once I closed(stop debugging in Xcode) the app and went back in the session was gone. The answer was to persist cookies like so to fix the problem:
NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"User"];
if ([cookiesData length] > 0) {
for (NSHTTPCookie *cookie in [NSKeyedUnarchiver cookiesData]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
这让我在尝试时遇到应用程序崩溃这样的事情。当我登录时,我设置了NSUserDefault,如下所示:
This gives me an app crash when I try to do something like this. When I log in I set the NSUserDefault like so:
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"User"];
//Then synthesize
这是错误的使用方法吗? NSHTTPCookieStorage甚至是我的问题吗?谢谢。
Is this the wrong way to use this? Is NSHTTPCookieStorage even my problem? Thanks.
推荐答案
使用以下命令,这是保存和加载适合我的cookie的正确方法:
Use the following, this is a correct way to save and load cookies that is working for me:
- (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];
}
}
希望有所帮助!
这篇关于AFNetworking自动保留Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!