SwiftUI:如何让按钮在 safari 中打开 URL?

Mar*_*adé 2 url button swift swiftui

我想要我的应用程序中的一个按钮,它将打开 safari 和一个特定的 URL 地址。我该怎么做呢?UIApplication.sharedApplication 似乎在 SwiftUI 中不起作用。

这是我在这里的第一个问题。如果我做错了什么,请提供反馈

cbe*_*r84 17

iOS < 13

Button(action: {
    self.someState.toggle()
    if let url = URL(string: "https://www.hackingwithswift.com") {
       UIApplication.shared.open(url)
   }
}) {
    Text("some label")
}
Run Code Online (Sandbox Code Playgroud)

iOS > 14

Link("My new Link", destination: URL(string: "https://www.mylinkcom")!)
Run Code Online (Sandbox Code Playgroud)

  • 您能否澄清一下:iOS&lt;13 和 iOS&gt;14。你的意思是iOS≤13吗? (2认同)

Ric*_*hiy 7

在视图中:

@Environment(\.openURL) private var openURL
Run Code Online (Sandbox Code Playgroud)

稍后,例如按下按钮时:

guard let url = URL(string: urlString) else { return }
openURL(url)
Run Code Online (Sandbox Code Playgroud)

了解更多: https: //developer.apple.com/documentation/swiftui/openurlaction