ChatGPT解决这个技术问题 Extra ChatGPT

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.


J
Josh Correia

It's not "baked in to Swift", but you can use standard UIKit methods to do it. Take a look at UIApplication's openUrl(_:) (deprecated) and open(_:options:completionHandler:).

Swift 4 + Swift 5 (iOS 10 and above)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.open(url)

Swift 3 (iOS 9 and below)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.openURL(url)

Swift 2.2

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.sharedApplication().openURL(url)    

Is there any chance from app store if we add some purchasing URL like this?
In iOS 10.0 you must now add options and handler: UIApplication.shared.open(URL(string:"google.com")!, options: [:], completionHandler: nil)
@gabicuesta You actually don't have to provide options and completionHandler, they default to [:] and nil, respectively
iOS14 not open link in Safari if setting "Default Browser" set to other like Google Chrome etc.
m
manncito

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:

https://i.stack.imgur.com/6pCEl.png


This is awesome. Thanks! Everyone who wants to show the Safari browser in an app extension should use this code. Accessing the sharedApplication property in app extension is forbidden. For more: developer.apple.com/library/archive/documentation/General/…
outstanding solution
Apple is sometimes rejecting apps from the store for using the old openURL method. This should now be the preferred solution.
C
CodeOverRide

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

Amit, No, because it's done explicitly as I have explained it is guarantee that requestUrl exist if let requestUrl = ...
yes, there are many way to do things. Learn the reason why you should use certain code in a situation instead of being a stubborn brat saying, "I'm right, therefore your wrong" mentality. Seems like you are new to programming this is my advise to you kid.
Amit: No, it doesn't work, you are simply wrong. In Swift 2 or 1.2. And no wonder, requestUrl is not an optional so you can't unwrap it with !.
I like this method better than the one from Mike S, because you do the nil check before sending the request.
updated for Swift4: if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") { UIApplication.shared.openURL(requestUrl as URL) }
O
Olcay Ertaş

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

How to verfiy and avoid reopening app Safari if it has been already opened. When lauching I got a warning/error LAUNCH: Launch failure with -10652/ <FSNode 0x10d50cf90> { isDir = y, path = '/Applications/Safari.app' }
r
ramchandra n

Swift 3 & IOS 10.2

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

Swift 3 & IOS 10.2


But note that using this version will stop your app running on iOS 9 and previous unless you version check it
O
Olcay Ertaş

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

C
Chris K

In Swift 1.2:

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

K
Kaptain

In Swift 2.0:

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

d
dqualias

if your using SwiftUI:

Link("Stack Overflow", destination: URL(string: "https://www.stackoverflow.com/")!)

O
Olcay Ertaş

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

s
sohil

Swift 5

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