0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUI時代のURLの開き方。君はまだUIApplicationを使っているのか!?

Posted at

はじめに

SwiftUIで開発していると、ついUIKitの癖でUIApplication.shared.open(url)と書いてしまいがちですが、実はSwiftUIには SwiftUI流のやり方があったのです。

基本形

@Environment(\.openURL) private var openURL

let url = URL(string: "https://www.yahoo.co.jp")!
openURL(url)

dismissと同じ感覚ですね。

openURLの結果を知りたい

@Environment(\.openURL) private var openURL

let url = URL(string: "https://www.yahoo.co.jp")!
openURL(url) { accepted in
    if !accepted {
        print("could not open url = \(url)")
    }
}

クロージャを追加すると結果が分かります。

Markdown中のリンクを開く

Text("Visit [Yahoo](https://www.yahoo.co.jp) for details.")



たった1行でこれができるとは!:heart_eyes:

リンクの開き方を差し替えたい

Text("Visit [Yahoo](https://www.yahoo.co.jp) for details.")
    .environment(\.openURL, .init { url in
        your_URL_Processor(url) // ここで独自のURL処理ができる.
        return .handled
    })

最後のreturn .handledって何? :thinking:

openURLAction.Resultです。
以下のバリエーションがあります。

  • return .handled
    URLは自前で処理したので、OSは何もしない。

  • return .systemAction
    URLを開く処理をOSに依頼する。
    何も指定しなければurlをそのまま開く。
    :point_down_tone2:のようにカスタマイズしたURLを渡すこともできる。

let customizedURL = URL(string: "https://www.youtube.com")!
return .systemAction(customizedURL)
  • return .discarded
    エラー発生など、URLを開く処理を破棄する。(何もしない)

MarkdownをAttributedStringに変換してから使う

// 改行するためには行末にスペース2個、そして改行。 または空行を入れる。
let markdown = """
Visit for details.  
[Yahoo](https://www.yahoo.co.jp).  
[Google](https://www.google.co.jp).
"""
let attributedString = try! AttributedString(markdown: markdown)
Text(attributedString)

スクリーンショット 2025-06-08 18.01.21.png

まとめ

SwiftUIでURLを開くなら、openURL でスマートに! :sunglasses:

開発環境

Xcode 16.4

参考文献

openURL
openURLAction
openURLAction.Result

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?