![[iOS13]SceneDelegateを使用したURL Schemeによるアプリ起動処理](https://www.yukiiworks.com/wp-content/uploads/2019/04/swift.png)
はじめに
iOS/SwiftにてURL Schemeを使用したアプリ起動時の処理について。
iOS13からはSceneDelegateが追加され書き方を調べたので備忘録としてメモ。
記述方法
はじめにざっくりサンプルを載せます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url, let components = URLComponents(string: url.absoluteString), let host = components.host else { return } if host == "login" { if let queryItems = components.queryItems { var id: Int? var password: String? for queryItem in queryItems { if let value = queryItem.value { // パラメータ取得 switch queryItem.name { case "id": if let id = Int(value) { id = id } break case "password": password = value break default: break } } } } } } |
上記はURL Schemeにてidとpasswordを渡してログインをさせるようなものを適当に想定しました。
まず、URL Schemeの処理は
func scene(_ scene: UIScene, openURLContexts URLContexts: Set)
こちらのメソッド内に書きます。(URL Scheme名はプロジェクトに設定済みのこと)
1 2 3 4 5 | guard let url = URLContexts.first?.url, let components = URLComponents(string: url.absoluteString), let host = components.host else { return } |
上記のコードでは、guard let文にてURL Scheme起動時にURL ComponentsとHostを取得しています。
そして、下記の部分ではHostがloginである(URLの形式が<URL Scheme名>://loginであれば処理する)場合に処理します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | if host == "login" { if let queryItems = components.queryItems { var id: Int? var password: String? for queryItem in queryItems { if let value = queryItem.value { // パラメータ取得 switch queryItem.name { case "id": if let id = Int(value) { id = id } break case "password": password = value break default: break } } } } } |
そしてその後にURLのパラメータを取得しています。
Ex) <URL Scheme名>://login?id=xxx&password=yyy であるところのxxxとyyy
これだけ取得できれば後はそれに応じた処理をするだけになります。
hostの分岐をすればhost毎に処理を変えられますし、パラメータも好きにできます。
以上です。
![[Swift]UITextViewでリンクはタップできるまま長押しとダブルタップでの選択を防ぐ方法](https://www.yukiiworks.com/wp-content/uploads/2019/04/swift-300x300.png)
![[Android][Kotlin]EditTextのキーボードの完了ボタンを検知する方法](https://www.yukiiworks.com/wp-content/uploads/2019/10/android-studio-e1585186990750-300x159.jpg)

![[Android]RecyclerViewで一番下にスクロールさせる方法](https://www.yukiiworks.com/wp-content/uploads/2019/10/android-studio-e1585186990750-150x150.jpg)
![[Laravel]name属性の配列要素をoldで取得する方法](https://www.yukiiworks.com/wp-content/uploads/2019/05/laravel-150x150.png)
![[iOS]XPC connection interruptedエラーについて](https://www.yukiiworks.com/wp-content/uploads/2019/09/Xcode-150x150.png)

![[Kotlin]0パディングした文字列を返すExtension](https://www.yukiiworks.com/wp-content/uploads/2019/04/kotlin-150x150.png)
