Search code examples
iosswiftcompletionhandlersfsafariviewcontroller

Handle completion if no success when opening url with SafariViewController


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

Solution

  • 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.