Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a Call From UIButton

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)
                }
            }
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading