iosswiftphone-numberphone-call

Calling a phone number in swift


I'm trying to call a number not using specific numbers but a number that is being called in a variable or at least tell it to pull up the number in your phone. This number that is being called in a variable is a number that I retrieved by using a parser or grabbing from a website sql. I made a button trying to call the phone number stored in the variable with a function but to no avail. Anything will help thanks!

    func callSellerPressed (sender: UIButton!){
 //(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)

 // This is the code I'm using but its not working      
 UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)

        }

Solution

  • Just try:

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

    assuming that the phone number is in busPhone.

    NSURL's init(string:) returns an Optional, so by using if let we make sure that url is a NSURL (and not a NSURL? as returned by the init).


    For Swift 3:

    if let url = URL(string: "tel://\(busPhone)"), UIApplication.shared.canOpenURL(url) {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
    

    We need to check whether we're on iOS 10 or later because:

    'openURL' was deprecated in iOS 10.0