Session is not maintained between UIWebView
Asked Answered
M

1

6

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

Mouton answered 16/2, 2016 at 10:10 Comment(2)
Consider trying WKWebView (iOS 8+). With it you can copy configuration 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
i am facing similar issue , kindly helpErving
K
0

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.

Karenkarena answered 27/4, 2016 at 19:41 Comment(1)
Thanks @Brian Nickel. I solved my issue in similar way, but forget to add the answerMouton

© 2022 - 2024 — McMap. All rights reserved.