【发布时间】:2017-01-25 14:09:33
【问题描述】:
openURL 在 Swift3 中已被弃用。谁能提供一些示例来说明在尝试打开 url 时替换 openURL:options:completionHandler: 的工作原理?
【问题讨论】:
openURL 在 Swift3 中已被弃用。谁能提供一些示例来说明在尝试打开 url 时替换 openURL:options:completionHandler: 的工作原理?
【问题讨论】:
你只需要:
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)
}
【讨论】:
String 上使用 + 运算符,而不是在 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 documentation了解更多详细信息。
【讨论】:
如果您想在应用程序内部打开而不是离开应用程序,您可以导入 SafariServices 并解决它。
import UIKit
import SafariServices
let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: 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)
}
}
【讨论】:
replacingOccurrences的正则表达式。
import UIKit
import SafariServices
let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: 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.
}
};
【讨论】:
这工作正常,不会离开应用程序。
if let url = URL(string: "https://www.stackoverflow.com") {
let vc = SFSafariViewController(url: url)
self.present(vc, animated: true, completion: nil)
}
【讨论】: