如何在Swift3中打开一个URL

时间:2016-09-17 12:32:33

标签: ios swift swift3

在Swift3中已弃用

openURL。任何人都可以提供一些关于替换openURL:options:completionHandler:在尝试打开网址时如何工作的示例吗?

7 个答案:

答案 0 :(得分:337)

您只需要:

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

答案 1 :(得分:32)

以上答案是正确的,但如果您想检查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 documentation了解更多详情。

答案 2 :(得分:21)

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

a[i][j] = a[i][j][1],a[i][j][0]

答案 3 :(得分: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)
    }
}

答案 4 :(得分: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.
    }


};

答案 5 :(得分:1)

import UIKit 
import SafariServices 

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

答案 6 :(得分:0)

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

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