How to open an URL in Swift?

openURL has been deprecated in Swift 3.

Can anyone provide some examples of how the replacement openURL:options:completionHandler: works when trying to open an url?

132573 次浏览

你只需要:

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,请检查 苹果文档以获得更多详细信息。

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
import WebKit


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)
import UIKit
import SafariServices


let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)

这可以正常工作,并且不会离开应用程序。

    if let url = URL(string: "https://www.stackoverflow.com") {
let vc = SFSafariViewController(url: url)
self.present(vc, animated: true, completion: nil)
}