Reputation: 2274
The task is quite simple. With a given urlString
open it when it is valid. This is what I tried:
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
showInvalidUrlAlert()
return
}
UIApplication.shared.open(url)
}
This work with this example: "https://www.google.de/?hl=de"
However when passing an invalid url, which is also possible in my application (for example: "asdfd") I get this error on the console but nothing happens in the app:
[default] Failed to open URL asdf: Error Domain=NSOSStatusErrorDomain Code=-50 "invalid input parameters" UserInfo={NSDebugDescription=invalid input parameters, _LSLine=252, _LSFunction=-[_LSDOpenClient openURL:options:completionHandler:]}
What is the best practice here?
Upvotes: 2
Views: 7805
Reputation: 517
Did the URL have a http
or https
scheme attached? to open a website, you must require the String
to have http(s). other wise the application won't know how to handle it, since it also handles other protocols.
...supports many common schemes, including the http, https, tel, facetime, and mailto schemes...
https://developer.apple.com/documentation/uikit/uiapplication/1648685-open
Upvotes: 6
Reputation: 54466
You may want to use the completionHandler
parameter:
func openURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
showInvalidUrlAlert()
return
}
UIApplication.shared.open(url, completionHandler: { success in
if success {
print("opened")
} else {
print("failed")
// showInvalidUrlAlert()
}
})
}
Upvotes: 3
Reputation: 11
Inside of guard
statement, you can throw
an exception created by your application instead only put a return
, like this:
guard let urlString = url, !urlString.isEmpty, let url = URL(string: urlString) else {
throw ErrorEnum.invalidURL
}
With this approach, you can catch the error and send a UI Feedback for the User where it calls de func openURL
.
Upvotes: 1