A. Marian
A. Marian

Reputation: 55

GET Device Name in Swift WKWebview

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!

Upvotes: 0

Views: 325

Answers (1)

heximal
heximal

Reputation: 10517

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

Upvotes: 1

Related Questions