Abdel Rahman Ellithy
Abdel Rahman Ellithy

Reputation: 17

Making a phone call with swift not working with certain numbers

I have been trying desperately for the past few hours to make a phone call with swift when I call this function.

    func callPhone(phoneNumber: String){
        guard let url = URL(string:"telprompt:\(phoneNumber)") else {
             print("failed to load url, phone number: \(phoneNumber)")

             return
        }
        UIApplication.shared.open(url)
    }

For some reason it doesn't work, I have researched online everywhere and still couldn't find a problem to why this wouldn't work. Some numbers would occasionally work, like if I tried "123456789" it would work. but if i try a different number it wouldn't work; The guard let statement doesn't work and the url would be empty. Please help me. Any feedback would be very much appreciated.

Edit: So I found out when it is not working but I am not sure how to solve it. It doesn't work when I get the phone number from apple maps, but when I hard code the phone number it works. Here is my full code:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var map: MKMapView!
let locationManager = CLLocationManager()
let regionMeters : Double = 10000

override func viewDidLoad() {
    super.viewDidLoad()

    map.delegate = self
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
    map.showsUserLocation = true
    if let location = locationManager.location?.coordinate {
        let region = MKCoordinateRegion.init(center: location, latitudinalMeters: regionMeters, longitudinalMeters: regionMeters)

        map.setRegion(region, animated: true)
    }
    searchLocations(search: "Restaurant")

}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let identifier = "Place"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

        if annotationView == nil {

            annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView!.canShowCallout = true

            let btn = UIButton(type: .contactAdd)

            annotationView!.rightCalloutAccessoryView = btn
        } else {
            annotationView!.annotation = annotation
        }

        return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let subtitle = view.annotation?.subtitle as! String
    let splitted = subtitle.components(separatedBy: "+")
    let number = splitted.last as! String
    let trimmedNumber : String = number.components(separatedBy: [" ", "-", "(", ")"]).joined()
    CallOnPhone(phoneNumber: trimmedNumber)

}
func searchLocations(search : String){
    let searchRequest = MKLocalSearch.Request()
    searchRequest.naturalLanguageQuery = search
    searchRequest.region = map.region

    let activeSearch = MKLocalSearch(request: searchRequest)
    activeSearch.start { (response, err) in
        if response == nil {
            print("no request")
        } else {
            for item in (response?.mapItems)!{
                let annotation = MKPointAnnotation()
                annotation.title = item.name

                if let phone = item.phoneNumber {
                    annotation.subtitle = "Phone Number: \(phone as String)"
                }

                annotation.coordinate = item.placemark.coordinate
                self.map.addAnnotation(annotation)
            }



        }
    }
}

@objc func CallOnPhone(phoneNumber: String){
    let newStringPhone = phoneNumber.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    print(newStringPhone)
    if newStringPhone != ""{
        if let url = URL(string: "tel://\(newStringPhone)"), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }

}

}

Thanks,

Upvotes: 1

Views: 1708

Answers (2)

n1m1
n1m1

Reputation: 969

Try trimming the phone number.

let myphone:String = phoneNumber.trimmingCharacters(in:.whitespacesAndNewlines)

Full code:

if let url = URL(string: "tel://\(myphone)"),UIApplication.shared.canOpenURL(url) {
        if #available(iOS 10, *) {
            UIApplication.shared.open(url, options: [:], completionHandler:nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    } else {
        Util.shared.showToast(message: "Can't make call from this device", view: self.view)
    }

Upvotes: 2

Yogesh Tandel
Yogesh Tandel

Reputation: 1754

Below code show calling a number on button click. Also removing space if phonenum has spaces.

var phoneNumber = "Phone Number: 1234567"
var finalNumber = ""

let number = phoneNumber.split(separator: ":")
let tempNum = "\(number.last ?? "")"
print(tempNum)
let trimmedNumber : String = tempNum.components(separatedBy: [" ", "-", "(", ")"]).joined()
print(trimmedNumber)
finalNumber = trimmedNumber
print(finalNumber)

btn_Call.addTarget(self, action: #selector(CallOnPhone), for: .touchUpInside)

@objc func CallOnPhone(sender:UIButton){
    let newStringPhone = finalNumber.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    print(newStringPhone)
    if newStringPhone != ""{
        if let url = URL(string: "tel://\(newStringPhone)"), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
    }

}

screenshot from iphone

Upvotes: 0

Related Questions