Search code examples
swiftmapsphone-number

Searching for & calling a phone number for a point of interest


I've created a piece of code that will search for a phone number associated with a pin dropped on the map in my app:

func doCall(_ mapView : MKMapView! , didUpdateUserLocation userLocation : MKUserLocation, placemark:MKPlacemark )
{
    let request = MKLocalSearchRequest()
    let searchBar = resultSearchController!.searchBar
    request.naturalLanguageQuery = searchBar.text
    let span =  MKCoordinateSpan(latitudeDelta: 0.00000000001, longitudeDelta: 0.0000000001)
    let search = MKLocalSearch(request: request)
    search.start {MKLocalSearchResponse, error in
        for item in (MKLocalSearchResponse?.mapItems)! as [MKMapItem]
        {
            let optionalString = item.phoneNumber
            if let unwrapped = optionalString
            {

                let center = MKLocalSearchResponse!.mapItems.first!.placemark.coordinate
                request.region = MKCoordinateRegion(center: center, span: span)
                print(unwrapped)
                let cleanUrl = unwrapped.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
                let url: URL = URL(string: "tel://" + (cleanUrl))!
                UIApplication.shared.openURL(url)
            }


    }
    }
}

However, this piece of code returns 10 phone numbers and asks to call each and every one of those 10. I want the code to return a single phone number that is associated with that point of interest and ask me to call it.


Solution

  • Consider adding a break statement.

    if cleanUrl != nil {
        let cleanUrl = unwrapped.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
        let url: URL = URL(string: "tel://" + (cleanUrl))!
                UIApplication.shared.openURL(url)
        break
    }
    

    So, once a telephone no. is found, an alert to call that no. will be shown and break statement will break the loop and alert will not be shown for rest of the phone numbers.