How to clear cookies for specific domain in iOS?

2020-07-24 09:23发布

问题:

I have searched almost all questions on StackOverflow for answer to my question. I haven't found any useful link or tutorial saying which way is best to clear cookies for particular domain. So please if someone could help me.

回答1:

I found solution myself. If you wish to delete entire cookies in your UIWebView do this.

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSHTTPCookie *cookie;
for (cookie in [storage cookies]) {
  NSLog(@"%@", cookie); // Print the deleted cookie.
  [storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];

If you wish to delete cookies specific to one site or domain do this.

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSHTTPCookie *cookie;
for(cookie in [storage cookies]) {
   if([[cookie domain] rangeOfString:@"siteName(or)domainName"].location != NSNotFound) {
     NSLog(@"cookie to be deleted:%@", cookie);
     [storage deleteCookie:cookie];
   }
 }

In above code i have used siteName (or) DomainName replace it with site for which you want to remove cookies. You must know that every domain has subdomain. If you give gobal domain name in that place it wont delete cookies for subDomains. For Example LinkedIn, it has many subDomains like in.linkedIn.com, api.linkedIn.com etc. If i give http://www.linkedin.com which is gobal domain name it wont delete cookies for subdomains.

NSHTTPCookie has domain property so use that to get all domain names and using rangeOfString: method of NSString get domains which has your String(for example linkedin). Than do deletion on it will delete cookies for all its domain.

I had no one for helping i hope at least my post will help someone in future.