简体   繁体   中英

Call phone action don't work in swift

Hello I've button action for call number , but when I used it don't call and nothing shows.

My codes under below.

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

Thank You !

Proper Swift 3.0 Code

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

In Swift 3.0 NSURL have changed to URL . And sharedApplciation changed to shared . Also OpenURL changed to open , they have added a bunch other parameters to the open method, you can pass empty dictionary in options and nil in the completionHandler .

Try this answer.

 @IBAction func callPhone(sender: AnyObject) {

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

            UIApplication.sharedApplication().openURL(url)

       }
    }

Please try following code it's use to solve your problem.

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

please note that:

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

as of iOS 10 openUrl is deprecated;

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

so i advice to use this code block to support also 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)
}

Latest Xcode , Latest Swift working codes.

use telprompt:// not tel

let myphone = "+134345345345"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM