2016-09-17 64 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)