如何在objective-c中保存cookie?

时间:2014-06-26 21:00:40

标签: ios objective-c cookies

如何保存Cookie,然后将其粘贴在查询中?我知道这是一个愚蠢的问题,但我找不到解决方案。

1 个答案:

答案 0 :(得分:6)

在第一次请求到服务器后写一些时间(授权 - 当cookie不需要通过时)

NSData *cookieData = [NSKeyedArchiver archivedDataWithRootObject:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
[[NSUserDefaults standardUserDefaults] setObject:cookieData forKey:@"ApplicationCookie"];
[[NSUserDefaults standardUserDefaults] synchronize];

然后,当应用程序每次从NSUserDefaults中拉出cookie时,如果它们在那里:

NSData *cookieData = [[NSUserDefaults standardUserDefaults] objectForKey:@"ApplicationCookie"];
if ([cookieData length] > 0) {
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
    for (NSHTTPCookie *cookie in cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
     }
}