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
WKWebView
(iOS 8+). With it you can copyconfiguration
property from the last used instance to a newly created and maybe this will preserve cookies. Alternatively, use one instance of UIWebView allover the app. – Linguistician