ios – AFNetworking自动持久化Cookie

前端之家收集整理的这篇文章主要介绍了ios – AFNetworking自动持久化Cookie前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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];
    }

}

希望有帮助!

猜你在找的iOS相关文章