LoginSignup
2
5

More than 1 year has passed since last update.

【SwiftUI】URLスキームを受け取る

Last updated at Posted at 2022-09-22

はじめに

TwitterのURLスキームはURLスキームの種類によって起動する画面が振り分けられます。
今回はその挙動をSwiftUIで再現してみます。

TwitterのURLスキーム

タイムラインタブ
twitter://timeline

検索タブ
twitter://search

メンションタブ
twitter://mentions

DMタブ
twitter://messages

URLスキームの設定

① プロジェクトを選択します
② メインターゲットを選択します
③ 「Info」を選択します
④ 「URL Type」を開きます
⑤ 「+」を押します
スクリーンショット 2022-09-22 18.42.57.png

⑥ 「Identifier」を設定する
⑦ 「URL Schemes」を設定する
スクリーンショット 2022-09-22 18.49.14.png

これで設定完了です。

サンプルの実装

import SwiftUI

struct ContentView: View {
    @Binding var index: Int
    var body: some View {
        TabView(selection: $index) {
            HomeView()
                .tabItem {
                    Image(systemName: "house")
                    Text("ホーム")
                }
                .tag(0)

            SearchView()
                .tabItem {
                    Image(systemName: "magnifyingglass")
                    Text("検索")
                }
                .tag(1)
            SettingView()
                .tabItem {
                    Image(systemName: "gearshape")
                    Text("設定")
                }
                .tag(2)
        }
    }
}

struct HomeView: View {
    var body: some View {
        Text("ホーム")
    }
}

struct SearchView: View {
    var body: some View {
        Text("検索")
    }
}

struct SettingView: View {
    var body: some View {
        Text("設定")
    }
}

こんな感じです。
simulator_screenshot_D2E46C53-B1E8-47AB-9C25-C8189C3846A3.png

振り分ける方法

想定されるURLスキームは以下の通りです。

ホームタブ
sample-scheme://

ホームタブ
sample-scheme://home

検索タブ
sample-scheme://search

設定タブ
sample-scheme://setting

import SwiftUI

@main
struct URLSchemeApp: App {
    @State var index: Int = 0
    var body: some Scene {
        WindowGroup {
            ContentView(index: $index)
                .onOpenURL { url in
                    switch url.host {
                    case "home":
                        index = 0
                    case "search":
                        index = 1
                    case "setting":
                        index = 2
                    default:
                        return
                    }
                }
        }
    }
}

ポイント
onOpenURLでURLスキームを受け取ることができます。

URLの部分抽出を使えばURLパラメータでも処理を分ける事が可能です。

完成形

URLスキームによって起動するタブが切り替えられている事が確認できました。
Simulator Screen Recording - iPhone 12 - 2022-09-22 at 19.05.37.gif

おわり

URLスキームをうまく使えばユーザーにとって使いやすいアプリになること間違いなしです!!

2
5
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
2
5