如何在 Swift 中打开 URL?

问题描述 投票:0回答:5

openURL
已在 Swift 3 中弃用。

任何人都可以提供一些示例来说明尝试打开网址时替换

openURL:options:completionHandler:
如何工作吗?

ios swift swift3
5个回答
413
投票

您所需要的是:

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

44
投票

以上答案是正确的,但如果您想检查自己

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 文档 了解更多详细信息。


39
投票

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

import UIKit
import SafariServices

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

8
投票

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

2
投票

我正在使用 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.
    }


};
© www.soinside.com 2019 - 2024. All rights reserved.