Making phone calls in Swift

For a recent client project, I had to implement the feature to make phone calls from the iOS app. I had never done this before and at the first moment, I wondered if was possible to do that on iOS due to the strong restrictions Apple usually sets on things like this.

But this time I was surprised by Apple and found that we can launch phone calls from our iOS apps using the url scheme: tel://.

public func callTo(phoneNumber: String) -> Bool {

    if !phoneNumber.isEmpty {
        if let url = URL(string: "tel://" + phoneNumber.onlyNumbers()) {
            if UIApplication.shared.canOpenURL(url) {

                UIApplication.shared.openURL(url)
                NSLog("Calling number \(phoneNumber.onlyNumbers())...")
                return true

            }
        }
    }

    return false

}

After make some basic checks to the phoneNumber string we only need to open the url scheme with UIApplication.shared.openURL(url) to launch the phone call.

And if you are asking yourself what the onlyNumbers String function does, here you are:

extension String {

    public func onlyNumbers() -> String {
        var res : String = ""
        for c in self.characters {
            switch (c) {
                case "0","1","2","3","4","5","6","7","8","9" :
                    res = res + String(c)

                default : break
            }
        }
        return res        
    }

}

Yes, I know it’s not very elegant but hey! it works :thumbsup:.

That’s all folks! Take care out there ;)

"Making phone calls in Swift" was originally published on 29 Sep 2016