调用 phone 操作在 swift 中不起作用

Call phone action don't work in swift

您好,我有呼叫号码的按钮操作,但是当我使用它时没有呼叫,也没有任何显示。

下面是我的代码。

  @IBAction func callPhone(sender: AnyObject) {
        UIApplication.shared().canOpenURL((NSURL(string: "tel://1234567890")! as URL))
    }

谢谢!

试试这个答案。

 @IBAction func callPhone(sender: AnyObject) {

            if let url = NSURL(string: "tel://9069118117") {

            UIApplication.sharedApplication().openURL(url)

       }
    }

请尝试使用下面的代码来解决您的问题。

if let url = NSURL(string: "tel://\(1234567890)") {
  UIApplication.sharedApplication().openURL(url)
}

正确的 Swift 3.0 代码

    if let url = URL(string: "tel://\(phoneNumber)") {
      UIApplication.shared().open(url, options: [:], completionHandler: nil)
    }

在 Swift 3.0 NSURL 中已更改为 URL。并且 sharedApplciation 更改为 shared。此外 OpenURL 更改为 open,他们向 open 方法添加了一堆其他参数,您可以在 optionsnil 中传递空字典 completionHandler.

请注意:

  • tel:// try to call direct the phone number;
  • telprompt:// shows you an alert to confirm call

截至 iOS 10 openUrl 已弃用;

@available(iOS, introduced: 2.0, deprecated: 10.0, message: "Please use openURL:options:completionHandler: instead") open func openURL(_ url: URL) -> Bool

所以我建议使用此代码块来支持 iOS < 9:

if #available(iOS 10, *) {
    UIApplication.shared.open(yourURL)

    // if you need completionHandler:
    //UIApplication.shared.open(yourURL, completionHandler: { (aBool) in })

    // if you need options too:
    //UIApplication.shared.open(yourURL, options: [:], completionHandler: { (aBool) in })

} else {
    UIApplication.shared.openURL(number)
}

最新Xcode最新Swift工作代码。

使用 telprompt:// tel

let myphone = "+134345345345"

 if let phone = URL(string:"telprompt://\(myphone)"), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.openURL(url)
        }