如何在Swift3中打开一个URL

Sha*_*ain 137 ios swift swift3

openURL已在Swift3中弃用.任何人都可以提供一些示例,说明openURL:options:completionHandler:在尝试打开网址时替换是如何工作的吗?

Dev*_*nal 366

所有你需要的是:

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)
}
Run Code Online (Sandbox Code Playgroud)


Nir*_*v D 34

以上答案是正确的,但如果你想检查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)")
    })
}
Run Code Online (Sandbox Code Playgroud)

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

UIApplication.shared.open(url, options: [:])
Run Code Online (Sandbox Code Playgroud)

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


Che*_*iri 25

如果您想在应用程序内部打开而不是离开应用程序,您可以导入SafariServices并将其解决.

import UIKit
import SafariServices

let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

  • 此方法是根据 iOS 指南的最佳实践 (2认同)

Dem*_*ese 7

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)
    }
}
Run Code Online (Sandbox Code Playgroud)