删除cookie UIWebView

时间:2011-09-27 09:43:58

标签: objective-c ios cookies uiwebview

如何删除UIWebView中的cookie?这段代码:

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

删除cookie但是当我重新启动我的应用程序时,NSHTTPCookieStorage中有相同的cookie。有时这段代码有效,但我想让它每次都有效。如何解决这个问题?

5 个答案:

答案 0 :(得分:7)

这对我有用:

NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];

NSArray *allCookies = [cookies cookies];

for(NSHTTPCookie *cookie in allCookies) {
    if([[cookie domain] rangeOfString:@"facebook.com"].location != NSNotFound) {
        [cookies deleteCookie:cookie];
    }
}

答案 1 :(得分:6)

尝试这样的事情:

NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray* facebookCookies = [cookies cookiesForURL:
                                    [NSURL URLWithString:@"http://login.facebook.com"]];
        for (NSHTTPCookie* cookie in facebookCookies) {
            [cookies deleteCookie:cookie];
        }

答案 2 :(得分:3)

删除单个cookie并不总是因某些奇怪的原因而起作用。要真正删除cookie,您需要存储非特定的cookie,然后重新加载它们,然后遍历所有cookie并删除它们,如此

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
   if (cookies != nil && cookies.count > 0) {
       for (NSHTTPCookie *cookie in cookies) {
           [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
       }
       [[NSUserDefaults standardUserDefaults] synchronize];
   }

答案 3 :(得分:0)

请务必致电:

[[NSUserDefaults standardUserDefaults] synchronize];

最终......像魅力一样......

答案 4 :(得分:0)

类似于前一个但更简单:

NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];

NSArray *allCookies = [cookies cookies];

for(NSHTTPCookie *cookie in allCookies) {
    if([[cookie domain] contains:@"facebook.com"]) {
        [cookies deleteCookie:cookie];
    }
}

"最佳答案"很糟糕,因为它允许删除指定具体URL的cookie。例如,您删除了" login.facebook.com"的cookie。但你可能会错过" www.login.facebook.com"