如何使用sharedHTTPCookieStorage删除cookie数据和用户默认?

时间:2015-02-24 15:26:19

标签: ios objective-c cookies

我在loginWithUserName中有一个注册和APIManager.m方法。在loginWithUserName方法中,我像这样设置cookie:

if ([[responseObject objectForKey:@"status_code"] isEqualToString:kStatusOk]) {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    self.cookie = cookies[0];
    NSLog(@"%@", self.cookie);
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:self.cookie];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:cookiesData forKey:@"savedCookie"];
    [defaults synchronize];
    NSLog(@"%@ \n\n\n RESPONSE OBJECT Obtained \n\n\n",responseObject);
    succes(responseObject);
} else {
    failure(responseObject);
}

我有一种加载已保存的Cookie的方法(我在登录或注册后在appDelegate中使用此方法):

(BOOL) loadSavedAuthCookie {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *cookieData = [defaults dataForKey:@"savedCookie"];
    if (cookieData) {
        id cookie = [NSKeyedUnarchiver unarchiveObjectWithData:cookieData];
        if ([cookie isKindOfClass:[NSHTTPCookie class]]) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            return YES;
        }
        else return NO;
    }
    else return NO;
}

我想创建一个注销按钮,我需要在我的APIManager.m中删除cookie。

2 个答案:

答案 0 :(得分:2)

NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]) {
    [storage deleteCookie:cookie];
}

答案 1 :(得分:0)

清除NSUserDefault:

NSString *domain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:domain];