はじめに
私は今までUIApplication.shared.open
を使用してURLを開いていましたが、openURL
という環境値が追加されていて、SwiftUIではこちらを使うべきなのでは??と思ったので記事にしておきます。
古い
import SwiftUI
struct ContentView: View {
var body: some View {
Button {
UIApplication.shared.open(URL(string: "https://qiita.com/SNQ-2001")!)
} label: {
Text("URLを開く")
}
}
}
新しい
import SwiftUI
struct ContentView: View {
@Environment(\.openURL) var openURL
var body: some View {
Button {
openURL(URL(string: "https://qiita.com/SNQ-2001")!)
} label: {
Text("URLを開く")
}
}
}
おわり
この辺は面白いことができそうなのでよく調べておきたいです
Text("Visit [Example Company](https://www.example.com) for details.")
.environment(\.openURL, OpenURLAction { url in
handleURL(url) // Define this method to take appropriate action.
return .handled
})