Call SFSafariViewController from UITabBarController and go back after "Done" pressed

987 Views Asked by At

I have a custom UITabBarController with custom button. When I click this button I open SFSafariViewController - here all works fine. But when I clicked to "done" button in SFSafariViewController its dismiss. but I can't return to UITabBarController, I see only background color which I added in app delegate window.

Sample code:

class TabBar: UITabBarController, UITabBarControllerDelegate, SFSafariViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }

    func setupCenterButton() {
        let centerButton = CenterButton(frame: CGRect(x: 0, y: 0, width: 74, height: 74))
        centerButton.layer.cornerRadius = 37
        centerButton.frame.origin.y = self.tabBar.frame.minY - 37
        centerButton.frame.origin.x = view.bounds.width/2 - 37
        centerButton.setImage(UIImage(named: "google"), for: .normal)
        centerButton.addTarget(self, action: #selector(openURL), for: .touchUpInside)
        view.addSubview(centerButton)
        view.layoutIfNeeded()
    }

    @objc func openURL() {
        let termsURL = SFSafariViewController(url: URL(string: "https://google.ru")!)
        termsURL.modalPresentationStyle = .currentContext
        termsURL.delegate = self
        self.present(termsURL, animated: true, completion: nil)
    }
}

How can I present UITabBarController after SFSafariViewController?

2

There are 2 best solutions below

0
On

I had same problem, I solved selecting another tab bar item programmatically when I tap "Done" on my SafariViewController. In my exemple I select first item of my tab bar.

import UIKit
import SafariServices
    
class WebViewController: UIViewController, SFSafariViewControllerDelegate {
        
    override func loadView() {

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url = URL(string: "<your website url>") else {
            return
        }

        let safariVC = SFSafariViewController(url: url)
        present(safariVC, animated: true, completion: {self.selectFirstTab()})
        
    }
    
    func selectFirstTab(){
        self.tabBarController?.selectedIndex = 0
    }

}
3
On
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    //To access the  Specific tabBar ViewController
    let tabBarController = storyboard?.instantiateViewController(withIdentifier: "IdentifierTabbar") as! TabBar
   // tabBarController.isComingFrom = "Settings" // Assign the Value                
    window?.rootViewController = tabBarController
}