2
votes

I know this has been answered in several related forms, but I have been twisting my brain for days trying to figure this out to no avail. I have tried every single solution I could find that seemed to be even remotely related.

I am using a WKWebView and loading the url of a website. On that website, a user will log in. In order to keep the user logged in, we need to maintain the session with a cookie. I have got this working perfectly on Android (using webview and cookies).

I need to figure the following out for iOS:

1) How to find cookie (if it already exists) and send it with the URLRequest.

2) How to make sure cookies are maintained between the app being opened and closed.

2
I am also facing this issue, is it solved now?Nishu_Priya
I actually did manage to solve this. Was partly my own foolishness. Will post my answer when I get a chance... Hopefully will be of use.gdd
@gdd Did you ever end up posting the answer or was it not of use? Seeing as how I have been stuck with this same exact situation for days now I'm kind of at my wit's end. I developed my app for Android and I'm now applying the same logic to develop the app (from scratch mind you) for iOS but so far this is what is holding me back the most.Kevin F.

2 Answers

4
votes

Ok, getting back to this months later :/

It was ridiculously simple. In the login page of the website I had embedded in the WKWebView, I was not clicking the 'remember me' checkbox. I went down a whole rabbit hole thinking that it had something to do with the cookie/s for the website never being saved, but I was never actually instructing it to do that.

Hope that helps anyone. My face is bruised from multiple facepalmings.

1
votes

This Code Work For me -

Add this code in ViewDidLoad Method

    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    preferences.javaScriptCanOpenWindowsAutomatically = true
    let wkUController = WKUserContentController()
    let cookieScript = WKUserScript(source: "document.cookie = 'Set-Cookie: sessionId =\(Defaults[AppConstants.UD_SESSION_ID].string!)';", injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
    wkUController.addUserScript(cookieScript)
    let wkWebConfig = WKWebViewConfiguration()
    wkWebConfig.userContentController = wkUController
    wkWebConfig.preferences = preferences
    // Adding webview
    webView = WKWebView(frame: self.view.bounds, configuration: wkWebConfig)

   var request = URLRequest(url: url)
    request.addValue("Set-Cookie: sessionId = \(Defaults[AppConstants.UD_SESSION_ID].string!)", forHTTPHeaderField: "Cookie")
    webView?.load(request)