[webview] Swift Open Link in Safari

I am currently opening the link in my app in a WebView, but I'm looking for an option to open the link in Safari instead.

This question is related to webview swift safari

The answer is


Swift 5

Swift 5: Check using canOpneURL if valid then it's open.

guard let url = URL(string: "https://iosdevcenters.blogspot.com/") else {
     return
}

if UIApplication.shared.canOpenURL(url) {
     UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Swift 5

if let url = URL(string: "https://www.google.com") {
    UIApplication.shared.open(url)
}

In Swift 2.0:

UIApplication.sharedApplication().openURL(NSURL(string: "http://stackoverflow.com")!)

since iOS 10 you should use:

guard let url = URL(string: linkUrlString) else {
    return
}
    
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

IOS 11.2 Swift 3.1- 4

let webView = WKWebView()

override func viewDidLoad() {
    super.viewDidLoad()
    guard let url = URL(string: "https://www.google.com") else { return }
    webView.frame = view.bounds
    webView.navigationDelegate = self
    webView.load(URLRequest(url: url))
    webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
    view.addSubview(webView)
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .linkActivated  {
        if let url = navigationAction.request.url,
            let host = url.host, !host.hasPrefix("www.google.com"),
            UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
            print(url)
            print("Redirected to browser. No need to open it locally")
            decisionHandler(.cancel)
        } else {
            print("Open it locally")
            decisionHandler(.allow)
        }
    } else {
        print("not a user click")
        decisionHandler(.allow)
    }
}

In Swift 1.2:

@IBAction func openLink {    
    let pth = "http://www.google.com"
    if let url = NSURL(string: pth){
        UIApplication.sharedApplication().openURL(url)
}

New with iOS 9 and higher you can present the user with a SFSafariViewController (see documentation here). Basically you get all the benefits of sending the user to Safari without making them leave your app. To use the new SFSafariViewController just:

import SafariServices

and somewhere in an event handler present the user with the safari view controller like this:

let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)

The safari view will look something like this:

enter image description here


Swift 3 & IOS 10.2

UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)

Swift 3 & IOS 10.2


UPDATED for Swift 4: (credit to Marco Weber)

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
     UIApplication.shared.openURL(requestUrl as URL) 
}

OR go with more of swift style using guard:

guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {
    return
}

UIApplication.shared.openURL(requestUrl as URL) 

Swift 3:

You can check NSURL as optional implicitly by:

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
     UIApplication.sharedApplication().openURL(requestUrl)
}

Examples related to webview

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? Android Webview gives net::ERR_CACHE_MISS message Swift Open Link in Safari How to load html string in a webview? how to display progress while loading a url to webview in android? Download file inside WebView How to pass html string to webview on android how to get html content from a webview? Android webview slow Android WebView not loading an HTTPS URL

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to safari

How to Inspect Element using Safari Browser What does the shrink-to-fit viewport meta attribute do? background: fixed no repeat not working on mobile Swift Open Link in Safari How do I make flex box work in safari? onClick not working on mobile (touch) window.open(url, '_blank'); not working on iMac/Safari HTML5 Video tag not working in Safari , iPhone and iPad NodeJS/express: Cache and 304 status code Video auto play is not working in Safari and Chrome desktop browser