如何在Swift3中打开一个URL

openURL已经在Swift3中被弃用了。 任何人都可以提供一些如何更换openURL:options:completionHandler:试图打开一个url时工作的例子?

所有你需要的是:

 guard let url = URL(string: "http://www.google.com") else { return //be safe } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } 

以上答案是正确的,但如果你想检查你可以canOpenUrl或不这样试试。

 let url = URL(string: "http://www.facebook.com")! if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) //If you want handle the completion block than UIApplication.shared.open(url, options: [:], completionHandler: { (success) in print("Open url : \(success)") }) } 

注意:如果你不想处理完成,你也可以这样写。

 UIApplication.shared.open(url, options: [:]) 

不需要编写completionHandler因为它包含默认值nil ,请查看Apple文档以获取更多详细信息。

Swift 3版本

 import UIKit protocol PhoneCalling { func call(phoneNumber: String) } extension PhoneCalling { func call(phoneNumber: String) { let cleanNumber = phoneNumber.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "") guard let number = URL(string: "telprompt://" + cleanNumber) else { return } UIApplication.shared.open(number, options: [:], completionHandler: nil) } } 

我正在使用macOS Sierra(v10.12.1)Xcode v8.1 Swift 3.0.1,以下是我在ViewController.swift中的工作:

 // // ViewController.swift // UIWebViewExample // // Created by Scott Maretick on 1/2/17. // Copyright © 2017 Scott Maretick. All rights reserved. // import UIKit class ViewController: UIViewController { //added this code @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Your webView code goes here let url = URL(string: "https://www.google.com") if UIApplication.shared.canOpenURL(url!) { UIApplication.shared.open(url!, options: [:], completionHandler: nil) //If you want handle the completion block than UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in print("Open url : \(success)") }) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }; 

如果你想打开应用程序本身,而不是离开应用程序,你可以导入SafariServices并解决。

 import UIKit import SafariServices let url = URL(string: "https://www.google.com") let vc = SFSafariViewController(url: url!) present(vc, animated: true, completion: nil)