How to delete cookies in UIWebView? This code:
NSArray* cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *cookie in cookies) {
[cookies deleteCookie:cookie];
}
deletes cookies but when I restart my application, there are same cookies in NSHTTPCookieStorage. Sometimes this code works, but i want to make it work everytime.How to solve this problem?
Try something like this:
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:@"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
This worked for me:
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *allCookies = [cookies cookies];
for(NSHTTPCookie *cookie in allCookies) {
if([[cookie domain] rangeOfString:@"facebook.com"].location != NSNotFound) {
[cookies deleteCookie:cookie];
}
}
deleting a single cookie does not always work for some odd reason. To truly get a cookie deleted you will need to store the not specific cookie and then reload them and then iterate through all cookies and delete them such as this
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
if (cookies != nil && cookies.count > 0) {
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
The similar for previous one but simplier:
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *allCookies = [cookies cookies];
for(NSHTTPCookie *cookie in allCookies) {
if([[cookie domain] contains:@"facebook.com"]) {
[cookies deleteCookie:cookie];
}
}
The "best answer" is bad because it allows to delete cookies for the specified concrete URLs. So for example you delete cookie for "login.facebook.com" but you may miss "www.login.facebook.com"
Make sure to call:
[[NSUserDefaults standardUserDefaults] synchronize];
in the end... Works like a charm...
来源:https://stackoverflow.com/questions/7567129/delete-cookies-uiwebview