问题
Is there a way to handle the case if SafariViewController
fails to open a url
like you can with UIApplication.shared.open
?
This is my function:
if ["http", "https"].contains(url.scheme?.lowercased() ?? "") {
// Can open with SFSafariViewController
let safariViewController = SFSafariViewController(url: url)
self.present(safariViewController, animated: true) {
// no bool given?
}
} else {
// Scheme is not supported or no scheme is given, use openURL
guard let url = URL(string: urlString) else {
self.showInvalidUrlAlert()
return
}
UIApplication.shared.open(url, completionHandler: { success in
if !success {
print("failed")
self.showInvalidUrlAlert()
}
})
}
回答1:
I don't think SFSafariViewController
provides much interaction/feedback with your app.
As per Apple documentation:
The user's activity and interaction with SFSafariViewController are not visible to your app, which cannot access AutoFill data, browsing history, or website data.
Choosing the Best Web Viewing Class
If your app lets users view websites from anywhere on the Internet, use the SFSafariViewController class. If your app customizes, interacts with, or controls the display of web content, use the WKWebView class.
As Apple suggests, you may want to take a look at WKWebView class.
回答2:
Make your presenter view controller to conform SFSafariViewControllerDelegate
.
class ViewController: SFSafariViewControllerDelegate
and set ViewController
as delegate of SafariViewController
safariViewController.delegate = self
Then handle load status whether it is successful using didCompleteInitialLoad delegate.
func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
// Handle loadStatus.
print(didLoadSuccessfully)
// if load unsuccessful, dismiss SFSafariViewController and try to open using openURL
if !didLoadSuccessfully {
controller.dismiss(animated: true) {
// UIApplication.shared.open(..
}
}
}
来源:https://stackoverflow.com/questions/63102385/handle-completion-if-no-success-when-opening-url-with-safariviewcontroller