8

My App connects to a server and based on a cookie the server will issue a different response.

Is it no possible to programmatically clear the cookie store, so that the server will not recognize my App when it contacts the server the next time.

I gathered that clearing the Cookies in the Settings.app does only apply for cookies within Safari.

Thanks very much for your comment.

Besi
  • 22,579
  • 24
  • 131
  • 223
  • 1
    You are aware of [`[NSHTTPCookieStorage sharedHTTPCookieStorage]`](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/Reference/Reference.html), yes? – Michael Dautermann Nov 16 '11 at 15:50
  • Now I am. Thanks for pointing this out. – Besi Nov 16 '11 at 15:52

3 Answers3

18

Okay... following up on my earlier comment (and hoping this is the solution you are looking for), you probably want to utilize:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:]

for each of the cookies for your site.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Please note that for some reason you can't call it with nil to delete all cookies.. – Niralp Apr 17 '14 at 13:58
  • @Michael can i clear the cookies in safari through an iOS application? – Ganesh Kumar Jan 08 '16 at 11:31
  • @GaneshKumar [unfortunately not](http://stackoverflow.com/questions/9632294/is-it-possible-to-change-ios-safari-settings-programmatically)... Apple wants users to decide when cookies and browser history is cleared. – Michael Dautermann Jan 10 '16 at 21:40
2

If you want your changes to the NSHTTPCookieStorage to be retained, you'll also want to call off to

[[NSUserDefaults standardUserDefaults] synchronize];

To prevent this from slowing down your app, you may also want to call this on a background thread like so:

dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

dispatch_async(backgroundQueue, ^{
    //TODO: Cookie deletion logic here
});

EDIT:

If you just need to disregard cookies altogether for a given NSURLRequest, you can do so with:

[request setHTTPShouldHandleCookies:NO];

Where request is your instance of NSURLRequest.

Brian Bethke
  • 154
  • 6
2

As mentioned by @Niralp it isn't possible to delete all cookies by passing nil to deleteCookie: on an instance of NSHTTPStorage. However, since iOS 8 there has been a removeFromDate: method that can be utilised to the same effect.

In Swift 4 this would be:

HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0))

That would remove all cookies in the app since the 1970 epoch which is likely suitable for most needs.

Ben Dodson
  • 352
  • 3
  • 12