Session is not supported between UIWebView

In my application, I am trying to login through a UIWebView. Upon successful use of cookies, the login value is set to NSHTTPCookieStorage . UIWebView has several pages of my applications open.

When a request for a specific web page is sent, it checks whether the user is registered or not based on cookies.

I verified that cookies are present in NSHTTPCookieStorage , but are not valid cookies on the server. That is, he considers the user as a registered user.

My code for loading UIWebView is as follows:

 let url = serverURL + urlString let urlRequest = NSMutableURLRequest(URL: NSURL(string: url)!) webPage.loadRequest(urlRequest) 

Even I tried using NSURLSession and set cookies as HTTPHeaderField. Below is my code:

 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 works correctly for several cases. I cannot find what could be the problem for cookies.

Any help would be appreciated.

Thank you in advance

+6
source share
1 answer

The following code does not do what you intend:

 for cookie in cookies!{ URLRequest.setValue(cookie.value, forHTTPHeaderField: cookie.name) } 

When cookies are sent via HTTP, they are sent in a Cookie header of the format:

 Cookie: cookie1=value1; cookie2=value2 

You create several headers with the name cookie, so your request looks like this:

 cookie1: value1 cookie2: value2 

The easiest way to create the correct headers is NSHTTPCookie.requestHeaderFieldsWithCookies(_:[NSHTTPCookie]) . Since you have not added any other headers, you can simply do:

 if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: serverURL)!) { URLRequest.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies) } 

Aside, you use different URLs for your request and for the search for cookies. They should be the same as cookies can be tied to specific paths in the domain.

0
source

All Articles