I have a database where the phone numbers are saved (either Landline or Mobile or both). Depending on the record fetch, if the user wants to call the number and the record has both the numbers, mobile and landline, how to give the user an option to choose the number.
@IBAction func makeCall(_ sender: Any) {
print ("------Phone Number-----")
print(landline)
print(phoneNumber)
let phone = "tel://";
let lline = landline
let url:NSURL = NSURL(string:phone+phoneNumber)!
let url2:NSURL = NSURL(string: phone+landline)!
UIApplication.shared.openURL(url as URL)
UIApplication.shared.openURL(url2 as URL)
}
Using the above code, it dials both the numbers but want to give the user to choose either one of it.
As and add on for weissja19 answer, you should add a canopenurl check before calling the openurl call itself. Also neater if the user does not see an action he cannot perform. I'd recommend you to use a code like this.
@IBAction func makeCall(_ sender: Any) {
print ("------Phone Number-----")
print(landline)
print(phoneNumber)
let phone = "tel://";
let lline = landline
let url:NSURL = NSURL(string:phone+phoneNumber)!
let url2:NSURL = NSURL(string: phone+landline)!
let alert = UIAlertController(title: 'Choose a number to call', message: 'Please choose which number you want to call', preferredStyle: .alert)
if UIApplication.shared.canOpenUrl(url as URL) {
let firstNumberAction = UIAlertAction(title: "Number 1", style: .default, handler: { _ in
UIApplication.shared.openURL(url as URL)
})
alert.addAction(firstNumberAction)
}
if UIApplication.shared.canOpenUrl(url2 as URL) {
let secondNumberAction = UIAlertAction(title: "Number 2", style: .default, handler: { _ in
UIApplication.shared.openURL(url2 as URL)
})
alert.addAction(secondNumberAction)
}
if alert.actions.count == 0 {
alert.title = "No numbers to call"
alert.message = ""
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
} else {
alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
}
self.presentViewController(alert, animated: true, completion: nil)
}