I would like to display a phone number in a SwiftUI Text (or any View), and then make it clickable so that it will open the \'Phone\'.
Is there a way to do this with
Make it a Button()
with an action, not a Text()
with a gesture.
Try this,
let strNumber = "123-456-7890"
Button(action: {
let tel = "tel://"
let formattedString = tel + strNumber
guard let url = URL(string: formattedString) else { return }
UIApplication.shared.open(url)
}) {
Text("123-456-7890")
}
From iOS 14, Apple provides us a Link view by default. So, you can just use this,
Link("Anyone can learn Swift", destination: URL(string: "https://ohmyswift.com")!)
For the previous versions of iOS, like iOS 13.0, you still have to use
Button("Anyone can learn Swift") {
UIApplication.shared.open(URL(string: "https://ohmyswift.com")!)
}
Thanks to Ashish's answer, I found the necessary code I needed to solve this:
In the action inside of the Button - you need to call this method:
UIApplication.shared.open(url)
to actually make the phone call / open a link in a SwiftUI View.
Of course, I didn't understand how to format my phone number at first, which I found in these answers:
How to use openURL for making a phone call in Swift?
Don't forget to add the 'tel://' to the beginning of your string/format it as URL..
The full code of what worked is
Button(action: {
// validation of phone number not included
let dash = CharacterSet(charactersIn: "-")
let cleanString =
hotel.phoneNumber!.trimmingCharacters(in: dash)
let tel = "tel://"
var formattedString = tel + cleanString
let url: NSURL = URL(string: formattedString)! as NSURL
UIApplication.shared.open(url as URL)
}) {
Text(verbatim: hotel.phoneNumber!)
}
Using iOS 14 / Xcode 12.0 beta 5
Use new link feature in SwiftUI for phone and email links.
// Link that will open Safari on iOS devices
Link("Apple", destination: URL(string: "https://www.apple.com")!)
// Clickable telphone number
Link("(800)555-1212", destination: URL(string: "tel:8005551212")!)
// Clickable Email Address
Link("apple@me.com", destination: URL(string: "mailto:apple@me.com")!)
KISS answer:
Button("url") {UIApplication.shared.open(URL(string: "https://google.com")!)}