NSHTTPCookieOriginURL is broken on iOS :(

A quick tip that might save someone a good few hours of bug hunting:

Under iOS it seems that when creating cookies via [NSHTTPCookie cookieWithProperties] that using NSHTTPCookieOriginURL will cause creation to fail. Instead you should pass the URL as two parts using CookieDomain and CookiePath.

E.g this will silently fail:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:
  [NSHTTPCookie cookieWithProperties:
    [NSDictionary dictionaryWithObjectsAndKeys:
      @"Name", NSHTTPCookieName,  
      @"Value", NSHTTPCookieValue,
      referringUrl, NSHTTPCookieOriginURL,
      nil
    ]
  ]
];

But this will work (referringUrl is an NSURL such as http://example.com/foo/bar)

NSHTTPCookie* cookie = [NSHTTPCookie cookieWithProperties:
    [NSDictionary dictionaryWithObjectsAndKeys:
      @"Name", NSHTTPCookieName,  
      @"Value", NSHTTPCookieValue,
      [referringUrl host], NSHTTPCookieDomain,
      [referringUrl path], NSHTTPCookiePath,
      nil
    ]
  ];   
CBD_ASSERT(cookie);
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

And you can see, this time there’s a handy assert to catch any problems early on. Sometimes it pays to break your code into multiple statements even when not strictly necessary.

This entry was posted in Programming and tagged , . Bookmark the permalink.

Comments are closed.