Search code examples
ioswkwebview

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.


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);
        }