Calling a phone number in swift

IosSwiftPhone NumberPhone Call

Ios Problem Overview


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)!)
            
        }

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

A self contained solution in iOS 10, Swift 3 :

private func callNumber(phoneNumber:String) {
    
  if let phoneCallURL = URL(string: "tel://\(phoneNumber)") {
        
    let application:UIApplication = UIApplication.shared
    if (application.canOpenURL(phoneCallURL)) {
        application.open(phoneCallURL, options: [:], completionHandler: nil)
    }
  }
}

You should be able to use callNumber("7178881234") to make a call.

Solution 3 - Ios

Swift 4,

private func callNumber(phoneNumber:String) {
    
    if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
        
        let application:UIApplication = UIApplication.shared
        if (application.canOpenURL(phoneCallURL)) {
            if #available(iOS 10.0, *) {
                application.open(phoneCallURL, options: [:], completionHandler: nil)
            } else {
                // Fallback on earlier versions
                 application.openURL(phoneCallURL as URL)
                
            }
        }
    }
}

Solution 4 - Ios

Swift 5: iOS >= 10.0

This solution is nil save.

Only works on physical device.

private func callNumber(phoneNumber: String) {
    guard let url = URL(string: "telprompt://\(phoneNumber)"),
        UIApplication.shared.canOpenURL(url) else {
        return
    }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Solution 5 - Ios

Swift 3.0 and ios 10 or older

func phone(phoneNum: String) {
    if let url = URL(string: "tel://\(phoneNum)") {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url as URL)
        }
    }
}

Solution 6 - Ios

The above answers are partially correct, but with "tel://" there is only one issue. After the call has ended, it will return to the homescreen, not to our app. So better to use "telprompt://", it will return to the app.

var url:NSURL = NSURL(string: "telprompt://1234567891")!
UIApplication.sharedApplication().openURL(url)

Solution 7 - Ios

Swift 3, iOS 10

func call(phoneNumber:String) {
        let cleanPhoneNumber = phoneNumber.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
        let urlString:String = "tel://\(cleanPhoneNumber)"
        if let phoneCallURL = URL(string: urlString) {
            if (UIApplication.shared.canOpenURL(phoneCallURL)) {
                UIApplication.shared.open(phoneCallURL, options: [:], completionHandler: nil)
            }
        }
  }

Solution 8 - Ios

Okay I got help and figured it out. Also I put in a nice little alert system just in case the phone number is not valid. My issue was I was calling it right but the number had spaces and unwanted characters such as ("123 456-7890"). UIApplication only works or accepts if your number is ("1234567890"). So you basically remove the space and invalid characters by making a new variable to pull only the numbers. Then calls those numbers with the UIApplication.

func callSellerPressed (sender: UIButton!){
        var newPhone = ""
        
        for (var i = 0; i < countElements(busPhone); i++){
            
            var current:Int = i
            switch (busPhone[i]){
                case "0","1","2","3","4","5","6","7","8","9" : newPhone = newPhone + String(busPhone[i])
                default : println("Removed invalid character.")
            }
        }
        
        if  (busPhone.utf16Count > 1){
        
        UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + newPhone)!)
        }
        else{
            let alert = UIAlertView()
            alert.title = "Sorry!"
            alert.message = "Phone number is not available for this business"
            alert.addButtonWithTitle("Ok")
                alert.show()
        }
        }

Solution 9 - Ios

I am using this method in my application and it's working fine. I hope this may help you too.

func makeCall(phone: String) {
    let formatedNumber = phone.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
    let phoneUrl = "tel://\(formatedNumber)"
    let url:NSURL = NSURL(string: phoneUrl)!
    UIApplication.sharedApplication().openURL(url)
}

Solution 10 - Ios

Many of the other answers don't work for Swift 5. Below is the code update to Swift 5:

let formattedNumber = phoneNumberVariable.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
        
if let url = NSURL(string: ("tel:" + (formattedNumber)!)) {
    if #available(iOS 10.0, *) {
        UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
    } else {
        UIApplication.shared.openURL(url as URL)
    }
}

PS:

  1. With most of the answers, I wasn't able to get the prompt on the device. The above code was successfully able to display the prompt.
  2. There is no // after tel: like most answers have. And it works fine.

Solution 11 - Ios

In Swift 3,

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

Solution 12 - Ios

I am using swift 3 solution with number validation

var validPhoneNumber = ""
    phoneNumber.characters.forEach {(character) in
        switch character {
        case "0"..."9":
            validPhoneNumber.characters.append(character)
        default:
            break
        }
    }
    
    if UIApplication.shared.canOpenURL(URL(string: "tel://\(validNumber)")!){
        UIApplication.shared.openURL(URL(string: "tel://\(validNumber)")!)
    }

Solution 13 - Ios

This is an update to @Tom's answer using Swift 2.0 Note - This is the whole CallComposer class I am using.

class CallComposer: NSObject {

var editedPhoneNumber = ""

func call(phoneNumber: String) -> Bool {
    
    if phoneNumber != "" {
        
        for i in number.characters {
            
            switch (i){
                case "0","1","2","3","4","5","6","7","8","9" : editedPhoneNumber = editedPhoneNumber + String(i)
                default : print("Removed invalid character.")
            }
        }
        
    let phone = "tel://" + editedPhoneNumber
        let url = NSURL(string: phone)
        if let url = url {
            UIApplication.sharedApplication().openURL(url)
        } else {
            print("There was an error")
        }
    } else {
        return false
    }
    
    return true
 }
}

Solution 14 - Ios

openURL() has been deprecated in iOS 10. Here is the new syntax:

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

Solution 15 - Ios

If your phone number contains spaces, remove them first! Then you can use the [accepted answer's][1] solution.

let numbersOnly = busPhone.replacingOccurrences(of: " ", with: "")

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

[1]: https://stackoverflow.com/a/27260056/1758701 "accepted answer's"

Solution 16 - Ios

Swift 3.0 solution:

let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)

Solution 17 - Ios

Here's an alternative way to reduce a phone number to valid components using a Scanner

let number = "+123 456-7890"

let scanner = Scanner(string: number)

let validCharacters = CharacterSet.decimalDigits
let startCharacters = validCharacters.union(CharacterSet(charactersIn: "+#"))

var digits: NSString?
var validNumber = ""
while !scanner.isAtEnd {
    if scanner.scanLocation == 0 {
        scanner.scanCharacters(from: startCharacters, into: &digits)
    } else {
        scanner.scanCharacters(from: validCharacters, into: &digits)
    }
    
    scanner.scanUpToCharacters(from: validCharacters, into: nil)
    if let digits = digits as? String {
        validNumber.append(digits)
    }
}

print(validNumber)

// +1234567890

Solution 18 - Ios

For swift 3.0

if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) {
    if #available(iOS 10, *) {
        UIApplication.shared.open(url)
    } else {
        UIApplication.shared.openURL(url)
    }
}
else {
    print("Your device doesn't support this feature.")
}

Solution 19 - Ios

> For Swift 4.2 and above

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

Solution 20 - Ios

let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)

Solution 21 - Ios

func phone(phoneNum: String) {
    if let url = URL(string: "tel://\(phoneNum)") {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url as URL)
        }
    }
}

Solution 22 - Ios

Swift 3.0 & iOS 10+

UIApplication.shared.openURL(url) was changed to UIApplication.shared.open(_ url: URL, options:[:], completionHandler completion: nil)

options and completion handler are optional, rendering:

UIApplication.shared.open(url)

https://developer.apple.com/reference/uikit/uiapplication/1648685-open

Solution 23 - Ios

For a Swift 3.1 & backwards compatible approach, do this:

@IBAction func phoneNumberButtonTouched(_ sender: Any) {
  if let number = place?.phoneNumber {
    makeCall(phoneNumber: number)
  }
}

func makeCall(phoneNumber: String) {
   let formattedNumber = phoneNumber.components(separatedBy: 
   NSCharacterSet.decimalDigits.inverted).joined(separator: "")
      
   let phoneUrl = "tel://\(formattedNumber)"
   let url:NSURL = NSURL(string: phoneUrl)!

   if #available(iOS 10, *) {
      UIApplication.shared.open(url as URL, options: [:], completionHandler: 
      nil)
   } else {
     UIApplication.shared.openURL(url as URL)
   }
}

Solution 24 - Ios

For iOS 10 and above use below code to make a call

let phoneNo = "1234567890"
guard let number = URL(string: "tel://" + phoneNo ) else { return}
UIApplication.shared.open(number, options: [:], completionHandler: nil) 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThomas MartinezView Question on Stackoverflow
Solution 1 - IosThomas MüllerView Answer on Stackoverflow
Solution 2 - IosZorayrView Answer on Stackoverflow
Solution 3 - IosTejaView Answer on Stackoverflow
Solution 4 - IosgrantespoView Answer on Stackoverflow
Solution 5 - IosGandomView Answer on Stackoverflow
Solution 6 - IosDipen GajjarView Answer on Stackoverflow
Solution 7 - IosLuAndreView Answer on Stackoverflow
Solution 8 - IosThomas MartinezView Answer on Stackoverflow
Solution 9 - IosAyath KhanView Answer on Stackoverflow
Solution 10 - IosMahendra LiyaView Answer on Stackoverflow
Solution 11 - IosVenkView Answer on Stackoverflow
Solution 12 - IosEmmettView Answer on Stackoverflow
Solution 13 - IosMichael McKennaView Answer on Stackoverflow
Solution 14 - IosTorre LasleyView Answer on Stackoverflow
Solution 15 - IosDisplay NameView Answer on Stackoverflow
Solution 16 - IosmazoratiView Answer on Stackoverflow
Solution 17 - IosAshley MillsView Answer on Stackoverflow
Solution 18 - IosHardik ThakkarView Answer on Stackoverflow
Solution 19 - IosiHarshilView Answer on Stackoverflow
Solution 20 - IosJithin Pankaj kView Answer on Stackoverflow
Solution 21 - IoshussainView Answer on Stackoverflow
Solution 22 - IosRLonielloView Answer on Stackoverflow
Solution 23 - IosLauren RothView Answer on Stackoverflow
Solution 24 - IosYogesh RathoreView Answer on Stackoverflow