In my app I'm trying to login user through UIWebView. On successful login cookies are set in NSHTTPCookieStorage
. Few of my app pages are open in UIWebView.
When request for particular web page is send, it check whether user is logged in or not based on the cookies.
I checked that cookies are present in NSHTTPCookieStorage
, but are not valid cookies on server. That is, it consider user as logged out user.
My code for loading UIWebView is as below:
let url = serverURL + urlString
let urlRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
webPage.loadRequest(urlRequest)
Even I tried with NSURLSession
and setting cookies as HTTPHeaderField. Below is my code for that too:
let URLRequest: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: url)!)
let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: serverURL)!)
for cookie in cookies!{
URLRequest.setValue(cookie.value, forHTTPHeaderField: cookie.name)
}
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithRequest(URLRequest)
task.resume()
It's working properly for few cases. I'm unable to find what can be an issue with the cookies.
Any help will be appreciated.
Thanks in advance
The following code does not do what you intend:
for cookie in cookies!{
URLRequest.setValue(cookie.value, forHTTPHeaderField: cookie.name)
}
When cookies are sent over HTTP, they are sent in a Cookie
header of the format:
Cookie: cookie1=value1; cookie2=value2
You are creating multiple headers named the cookie name, so your request looks like:
cookie1: value1
cookie2: value2
The easiest way to create the correct headers is with NSHTTPCookie.requestHeaderFieldsWithCookies(_:[NSHTTPCookie])
. Since you've added no other headers, you could simply do:
if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: serverURL)!) {
URLRequest.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
}
As an aside, you are using different URLs for your request and for looking up the cookies. They should be the same as cookies can be scoped to specific paths in a domain.