In my project I am trying to make a phone call when the UI button is topped. Below is the implementation but when I run it from the Simulator or on my iPhone it doesn't work. How do I fix it?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ListOfCarsTableViewCell
let carsIndex = carsArray[indexPath.row]
cell.phoneButton.setTitle(carsIndex.dealer.phone.toPhoneNumber(), for: .normal)
return cell
}
@objc func callTapped(_ sender: UIButton) {
let buttonPosition = sender.convert(CGPoint.zero, to: self.tableView)
if let indexPath = tableView.indexPathForRow(at: buttonPosition){
let phoneNumber = carsArray[indexPath.row].dealer.phone
callNumber(phoneNumber: phoneNumber)
}
}
func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
}
}
}
CodePudding user response:
Add "tel://" on your url string
func callNumber(phoneNumber:String) {
if let url = URL(string: "tel://\(phoneNumber)") {
UIApplication.shared.open(url, options: [:]) { success in
if success {
print("Making phone call")
} else {
print("Something went wrong while making phone call")
}
}
} else {
print("Failed to make phone call")
}
}
Edit: I look that callTapped action is not connected with your phonebutton. Please add the following line at cellForRowAt function. It will work perfectly.
cell.phoneButton.addTarget(self, action: #selector(callTapped(_:)), for: .touchUpInside)
CodePudding user response:
You can try
cell.phoneButton.tag = indexPath.row
cell.phoneButton.setTitle(carsIndex.dealer.phone.toPhoneNumber(), for: .normal)
cell.phoneButton.addTarget(self, action: #selector(callTapped), for: .touchUpInside)
@objc func callTapped(_ sender: UIButton) {
let phoneNumber = carsArray[sender.tag].dealer.phone
callNumber(phoneNumber: phoneNumber)
}
Also Don't forget to add tel://
before phone number