Answers:
所有你需要的是:
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文档。
如果您想在应用程序内部打开而不是离开应用程序,则可以导入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
。
我正在使用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.
}
};