Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Close and open app and keep the last url visited in iOS webview

I wish to open app with the latest url viewd on a webview ios app.
Tryied this inside viewdidload()

    var hasHistoryUrl = false
    WebView.evaluateJavaScript("window.location.href") {
        (result,error)->Void in if (result != nil){
            hasHistoryUrl=true
        }
    }
    
    if (hasHistoryUrl){
       // let url = URL(string: historyUrl)
    } else {
        let url = URL(string: "https://www.url.com/")
        let request = URLRequest(url: url!)
        loadReq(request: request);
    }

Not working on true device, on emulators allways opens with a clear cache.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you open your app, all variable initialise and your previous data will be gone. So you need to save latest visited url in userdefaults as string like-

let url: String = "abcd.com"
UserDefaults.standard.set(url, forKey: "MyUrl")

And fetch url from userdefaults when you open the app as –

if let urlString = UserDefaults.string(forKey: ""MyUrl"") {
    // Do stuff
}

In your code, insert it as-

    WebView.evaluateJavaScript("window.location.href") {
        (result,error)->Void in if (result != nil){
            UserDefaults.standard.set(yourURL, forKey: "MyUrl")
        }
    }
    
    if let urlString = UserDefaults.string(forKey: ""MyUrl"") {
        // Do stuff
    } else {
        let url = URL(string: "https://www.url.com/")
        let request = URLRequest(url: url!)
        loadReq(request: request);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading