0

How can i get the device name in swift5 and send it with the wkwebview url. If i print the name i get the model name but with the following code i get the error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

 let name = UIDevice.current.name
 let url = URL(string: "mydomain/index.php?token=\(token ?? "")&model=\(name)")!
 webView.load(URLRequest(url: url))

I need the device name and token to store in a mysql database. Thank You!

A. Marian
  • 55
  • 8

1 Answers1

1

you try to unwrap (! operator at the end of 2nd line) unsafe expression. URL constructor doesn't recognize the string you pass as string: parameter as valid url. it returns nil and causes fatal error. try to refactor your code to make it more safe:

let urlStr = "mydomain/index.php?token=\(token ?? "")&model=\(name)"
print("trying to load url \(urlStr)")
if let url = URL(string: urlStr) {
   webView.load(URLRequest(url: url))
}

UPDATE: followed by this SO question the code must be slightly refactored:

let urlStr = "mydomain/index.php?token=\(token ?? "")&model=\(name)"
print("trying to load url \(urlStr)")
if let url = URL(string: urlStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)) {
   webView.load(URLRequest(url: url))
}
heximal
  • 10,327
  • 5
  • 46
  • 69
  • I don't have the error anymore, but webview don't load the URL – A. Marian May 21 '20 at 13:51
  • your url is not valid. you should specify full url like http ://example.com/index.php?token=\(token ?? "")&model=\(name) – heximal May 21 '20 at 13:53
  • mydomain is just an example. In my code is the full url. – A. Marian May 21 '20 at 13:58
  • Still not loading the url. Print result is: WF: _WebFilterIsActive returning: NO https://myurl/index.php?token=ePtIACpD_0FthMoi2Y7bKi:APA91bGzCs226WKrFySV2ef7ZZZecEE2DSJ1DEC_mofYyVLtHvyaBZrqyfEPkhYTQ8-w5r1bkzQhpOQ8g-3dADYWk_W8l3ffr2B_8CX40JzryMtXEqZdfx7PFU__C8aD_-EzbvVomrR7&model=Simulator iPhone12,5 – A. Marian May 21 '20 at 14:17
  • ah, you see? space character in "Simulator iPhone12,5" probably breaks the url – heximal May 21 '20 at 14:20
  • I replaced urlHostAllowed with urlQueryAllowed and now it,s ok. Thank you! – A. Marian May 21 '20 at 18:05