Open URL in specific TabBar

Viewed 854

I am implementing a "Tabbet App" and I need a "Tab" to open a URL in Safari (new window not in the same viewcontroller)

Currently for example in the viewcontroller of Tab4 (Tab4ViewControllerView.swif) I have added the following code:

  guard let url = URL(string: "https://google.com") else {
        return //be safe
    }

    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    } else {

        UIApplication.shared.openURL(url)
    }

It works but when I return from Safari to the application, Tab4 is selected and since it does not contain anything it looks white.

I need to click on Tab4 to open Safari but it should not be selected (you must keep selecting the previous tab.)

In the example of the image: I am currently in Tab1 and pressing Tab4 should open Safari but keeping selected Tab1

sample

2 Answers

Add to your UITabBarController extension with UITabBarControllerDelegate, also set to your Tab 4 restoration Id

restoration id for tab

TabBarController

in TabBarViewContoller add:

import UIKit

class TabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        // Do any additional setup after loading the view.
    }
}

extension TabBarViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if viewController.restorationIdentifier == "safariTabViewController" {
            if let url = URL(string: "your_url"), UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.openURL(url)
            }
            return false
        }
        return true
    }
}

when you returning false in delegate - you make sure that tab will not be switched

You should embed a webView in tab4, using WKWebView or UIWebView. This way you won't have to leave your application.

Something like,

let webView = WKWebView()



override func loadView() {
    self.view = webView
}


if let url = URL(string: "https://www.apple.com") {
    let request = URLRequest(url: url)
    webView.load(request)
}
Related