How to create tappable url/phone number in SwiftUI

KISS answer:

Button("url") {UIApplication.shared.open(URL(string: "https://google.com")!)}

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

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("[email protected]", destination: URL(string: "mailto:[email protected]")!)
    

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

Tags:

Swiftui