HowTo —— Use Link or openURL to open URL scheme in SwiftUI2.0

Published on

Get weekly handpicked updates on Swift and SwiftUI!

SwiftUI 2.0 provides native support for opening URL schemes, which makes it very convenient to call other apps in code.

Similar to NavigationLink, open the URL scheme directly to the corresponding app

Swift
Link("openURL",destination:safariUrl)

openURL

In SwiftUI 2.0, Apple provided some methods to invoke system operations by injecting them through Environment, such as exportFiles, importFiles, openURL, etc.

Swift
@Environment(\.openURL) var openURL
openURL.callAsFunction(url)

Code Example

Swift
struct URLTest: View {
    @Environment(\.openURL) var openURL
    
    let safariUrl = URL(string:"http://www.apple.com")!
    let mailUrl = URL(string:"mailto:foo@example.com?cc=bar@example.com&subject=Hello%20Wrold&body=Testing!")!
    let phoneURl = URL(string:"tel:12345678")!
    
    var body: some View {
        List{
            Link("Use Safari to open web page",destination:safariUrl)
            
            Button("Send email"){
                openURL.callAsFunction(mailUrl){ result in
                    print(result)
                }
            }
            
            Link(destination: phoneURl){
                Label("Make a phone call",systemImage:"phone.circle")
            }
        }
    }
}

The simulator only supports very few URL schemes, it’s best to test on a real device

Some URL schemes provided by Apple

I'm really looking forward to hearing your thoughts! Please Leave Your Comments Below to share your views and insights.

Fatbobman(东坡肘子)

I'm passionate about life and sharing knowledge. My blog focuses on Swift, SwiftUI, Core Data, and Swift Data. Follow my social media for the latest updates.

You can support me in the following ways