Search code examples
swiftuiwebviewwkwebviewuiwebviewdelegatesfsafariviewcontroller

How to dismiss SFSafariViewController on UIView


class CustomScreen: UIView, SFSafariViewControllerDelegate {
@IBAction func webPageBtnAction(_ sender: Any) {
    if #available(iOS 9.0, *) {
        let svc = SFSafariViewController(url: NSURL(string: "https://stackoverflow.com/")! as URL)
        svc.delegate = self
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = svc
    } else {
        // Fallback on earlier versions
    }
}

@available(iOS 9.0, *)
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    controller.dismiss(animated: false, completion: nil)
}
}

In some reason i am not able to dismiss the SFSafariViewController. Any idea?


Solution

  • Since in your code you are replacing the rootViewController (is a bad practice for such scenario), you should simple present the SFSafariViewController doing so:

    let svc = SFSafariViewController(url: NSURL(string: "https://stackoverflow.com/")! as URL)
    svc.delegate = self
    UIApplication.shared.keyWindow?.rootViewController?.present(svc, animated: true, completion: nil)
    

    As far as I can see it's a bad practice because the safariViewControllerDidFinish will never be called since CustomScreen will be deallocated from the replacement of the current rootViewController