Member-only story
Create a Telephone Call in SwiftUI
Get the user to call!
2 min readOct 30, 2023
Difficulty: Beginner | Easy | Normal | Challenging<br/>
This article has been developed using Xcode 12.4, and Swift 5.7.2
The background to this is I wanted to make a native call from a SwiftUI App. I mean how hard can that be?
The approach
I wanted to make sure I could make a telephone call from within a SwiftUI App. It turns out that using MVVM didn’t make this task any more difficult really than doing it straight.
Sure I needed to create a protocol for UIApplication
to conform to so it can be injected in the view model.
protocol OpenURLProtocol {
func open(_ url: URL)
}
extension UIApplication: OpenURLProtocol {
func open(_ url: URL) {
open(url, options: [:], completionHandler: nil)
}
}
that can then be injected using initilizer dependency into the view model.
final class ViewModel: ObservableObject {
let openURL: OpenURLProtocol
init(openURL: OpenURLProtocol = UIApplication.shared) {
self.openURL = openURL
}
func callNumber() {
guard let url = URL(string: "tel://08000480408") else { return }
openURL.open(url)
}
}