Thursday, February 4, 2016

Objective C Cookies

Some service call or sites create cookies in the device for their functional needs. It is our choice to accept those cookies or not. For that we have cookie policy to set at the time of application launch or at the time of calling a service or opening a site in web view.


We can set cookie accept policy using the NSHTTPCookieStorage class as shown below.

   [[NSHTTPCookieStorage sharedHTTPCookieStorage

Here I have set to accept cookies always. 

Below are the different cookie accept policies.

  •     NSHTTPCookieAcceptPolicyAlways,
  •     NSHTTPCookieAcceptPolicyNever,
  •     NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain

We can delete these cookies or set our own cookies for an URL Whenever we need based on our requirement as shown below.

   NSHTTPCookieStorage *cStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

   for (NSHTTPCookie *each in cStorage.cookies) {

       [cookieStorage deleteCookie:each];

   [[NSUserDefaults standardUserDefaults] synchronize];

I haven taken all the cookies in the storage and removing them. We can also delete cookies for a particular URL using the cookiesForURL method of NSHTTPCookieStorage as shown below.

   NSHTTPCookieStorage * cStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

   NSArray *cookies = [cStorage cookiesForURL:[NSURL 
   for (NSHTTPCookie *each in cookies) {
        [cookieStorage deleteCookie:each];

   [[NSUserDefaults standardUserDefaults] synchronize];


Hope this post is useful. Feel free to comment in case of any queries.