プログラム関係の備忘録。技術系記事1000記事以上を目指すブログ

【SwiftUI】外部ブラウザでURLを開きたいときはLinkが使える

  • 2021年2月26日
  • 2021年2月26日
  • Swift
  • 2550view
  • 0件

初めに

Swiftのコードからリンクを外部ブラウザで開きたいとき。
これまではUIApplication.shared.open~としていたのですが、iOS14からはとっても簡単になったよう。

UIApplicationを使う方は以下など参考に。
https://weblabo.oscasierra.net/swift-shared-openurl-safari/

Linkの使い方

ごく一般的な使用方法

Link("googleを開く", destination: URL(string: "https://google.com")!)

テキストを装飾したい場合

Link("googleを開く",
      destination: URL(string: "https://google.com")!)
    .font(.title)
    .foregroundColor(.blue)

コードから利用したい場合

例えばボタンのアクション内に仕込みたい場合や、alertのアクションとして仕込みたいときなど。

struct anyView: View {
    @Environment(\.openURL) var openURL

    var body: some View {
        Button("Visit Apple") {
            openURL(URL(string: "https://www.apple.com")!)
        }
    }
}
struct anyView: View {
    @Environment(\.openURL) var openURL

    @state private var someAlert = false

    var body: some View {
        Button(action: {

          self.someAlert = true
        }) {
          Text("alertの結果によって使う")
        }
        .alert(isPresented: $someAlert){
          title: Text("はいを押すと外部リンク飛ぶ"),
          primaryButton: .default(Text("はい"), action: {
            openURL(URL(string: "https://google.com")!)
          }),
          secondaryButton: .destructive(Text("いいえ"))
        }
    }
}

以上です