2016-09-17 111 views

回答

233

所有你需要的是:

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

如果我在我的网址中使用“+”运算符,该怎么办?例如:“https://xxxxx.com./xxxxxxxxxxxxxx="+userName+"xxxxxxx="+userPass+"&xxxxxxxxx”就是这样。该字符串给了我一个错误“否'+'候选人产生预期的上下文结果类型'网址' –

+0

你必须在'字符串'上使用+运算符而不是'URL' –

+0

注意:不要尝试执行这个:UIApplication.shared.openURL(URL(string:“insert url here”)!)。 XCode 8上的编译器会感到困惑,无法正确构建。因此,请按原样使用此解决方案。很棒!谢谢。 – Joel

19

以上的答案是正确的,但如果你想查询你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更多细节。

6

斯威夫特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) 
    } 
} 
+0

您可以使用'replacesOccurrences'的正则表达式。 – Sulthan

2

我使用MacOS的塞拉利昂(v10.12.1)的Xcode V8.1斯威夫特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 

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


}; 
6

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

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