Currently, I have created a button that, when tapped, launches a phone number as a hyperlink in SwiftUI:

Button(action: {
    guard let phoneNum = URL(string: "tel://1-123-456-7890") else {return}
    UIApplication.shared.open(phoneNum)
}) {
    Text("Call number")
}

The issue is that this, when clicked, first opens up a prompt asking "Call 1 (123) 456-7890?" with the chance to cancel. Thus, this button isn't a one click option to automatically begin a phone call.

Is there a simple way that a button, when being tapped, automatically launches a phone call after a single tap without having that prompt in between?

I was hoping that this code above would automatically launch a phone call, like what happens when you use URL in SwiftUI to open up a webpage with one tap. However, with phone numbers, there seems to be the prompt in between.

Edit: If not a simple solution, is there any solution that retains this style of having a button that launches a phone number from a string?

1

There are 1 best solutions below

1
Ramzi Bouchedoub On

Yes, you can achieve this using the CallKit library in iOS. This library allows your application to initiate phone calls without user confirmation. Here's how to achieve this in SwiftUI:

First, make sure you have added this permission in the application's Info.plist file:

<key>NSMicrophoneUsageDescription</key>

<string>We need access to your microphone to make calls.</string>

Then you can use the following code to make the call:

import SwiftUI
import CallKit

  struct ContentView: View {
    let callController = CXCallController()

var body: some View {
    Button(action: {
        let handle = CXHandle(type: .generic, value: "1234567890") 
        let startCallAction = CXStartCallAction(call: UUID(), handle: handle)
        let transaction = CXTransaction(action: startCallAction)
        
        callController.request(transaction) { error in
            if let error = error {
                print("Failed to start call: \(error.localizedDescription)")
            } else {
                print("Call started successfully")
            }
        }
    }) {
        Text("Call number")
    }
}

}