WKWebview iOS (swift) : Keep session connected after app closed

Viewed 4867

I want to make an app from a PWA on iOS using a simple WKWebView. I've managed to implement it in a simple ViewController and it is working fine.

Problem : when i login and then quit the app, the session is lost and i have to login again.

Question : Is it possible to keep the session informations after the user quit the app ?

Thanks in advance for your answers !

2 Answers

You need to look into persisting your session data. For WKWebView, all of that is part of WKProcessPool. So when your app goes into the background, you need to look into persisting the WKProcessPool session, and when you use your web view, always use that same WKProcessPool instance.

Here's an answer that may help you save that data to your UserDefaults. https://stackoverflow.com/a/52109021/2658489

I think you should implement login API, for authorization and Login UI on Native App, and then you can have dashboard items using single WKWebView controller.

When a user logged in with the native page - loginViewController, you should store user name, password (maybe encrypted) in user preferences, e,g.

 UserDefaults.standard.set(userName, forKey: keyUserName)
 UserDefaults.standard.set(userPassword, forKey: keyPassword)
 UserDefaults.standard.synchronize()

Next time (after quit App) when you back you can check for auto login in AppDelegate - didFinishLaunchingWithOptions e.g.

if let username = UserDefaults.standard.value(forKey: keyUserName) as? String,
        password = UserDefaults.standard.value(forKey: keyPassword) as? String
    {
            /// DO AUTOLOGIN .. CALL API AND LAND TO DASHBOARD PAGE (WKWebView)..
    }
Related