![[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)
![[超簡単!]情報処理試験のための論理回路の覚え方](https://www.yukiiworks.com/wp-content/uploads/2019/03/code1211IMGL1494_TP_V4-150x150.jpg)
![[Python]tkinterのScrolledTextで末尾にスクロールさせる方法](https://www.yukiiworks.com/wp-content/uploads/2019/11/python-logo-150x150.png)
![[Google Play Console]アップロードできませんでした Android App Bundle は署名されていません。エラーについて](https://www.yukiiworks.com/wp-content/uploads/2019/06/google-play-150x150.jpg)
![[Flutter]chopper_generator使用時にbuild_runnerのビルドが完了しない問題の解消法](https://www.yukiiworks.com/wp-content/uploads/2020/08/flutter-150x150.png)
![[bootstrap-tagsinput]タグ入力欄でEnterキー押下時にSubmitさせない方法](https://www.yukiiworks.com/wp-content/uploads/2019/05/javascript-150x150.png)
![[Android]WebViewでスクロールをバウンドさせない方法](https://www.yukiiworks.com/wp-content/uploads/2019/10/android-studio-e1585186990750-150x150.jpg)

