store url in userdefaults

Viewed 2585

I am calling API wih 'Alamofire'. In my response I get one weblink. I store that weblink in to one variable. Now I want to store that weblink into the local database. so I use 'userdefaults'. But when I retrive that weblink into the other 'viewcontroller' at that time my weblink changed and web page didnot open.

let weblink = datastring["Web_Link"] as! String
UserDefaults.standard.set(weblink, forKey: "Link") 

for these I use this

UserDefaults.standard.set(url: URL?, forKey: String) 

and in another 'viewcontroller'

let url = UserDefaults.standard.url(forKey: "Link") 

for these I used

let url = UserDefaults.standard.url(forKey: String)

and my other code is

 let request = URLRequest.init(url: url!)

 self.webview.load(request)

my url example is "https://example.com/"

but when I retrive at that time url is

'https:/example.com'

so my webpage cannot open. I am using wkwebview.

2 Answers

You store the url as string so retrieve it like this.

let url = UserDefaults.standard.string(forKey: "Link") 

It looks like you are storing String value in user defaults and trying to get URL from UserDefaults. So Please try as like below.

let weblink = datastring["Web_Link"] as! String

if let URL = URL(string: weblink){

    UserDefaults.standard.set(URL, forKey: "Link")
}
Related