##はじめに
実装したいものはこれ。
クイックアクション(or3DTouch?) という名前らしく、
検索する際に少し苦戦したのであえて記事のタイトルは
このようにしている。
##実装手順
###必要なもの
・Info.plist
・SceneDelegate
####Info.plist
Info.plistをSourceCodeで開き、以下のコードを追加
今回は静的に設定していますが、コードでも動的に設定ができます。
後者は一度アプリが起動していないと反映されないので、
個人的には静的に設定するのをお勧めしたいです。
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemType</key>
<string>ショートカットアイテムタイプ1</string>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypeSearch</string>
<key>UIApplicationShortcutItemTitle</key>
<string>表示タイトル1</string>
<key>サブタイトル1</key>
<string>Search for an item</string>
</dict>
<dict>
<key>UIApplicationShortcutItemType</key>
<string>ショートカットアイテムタイプ2</string>
<key>UIApplicationShortcutItemIconType</key>
<string>UIApplicationShortcutIconTypeShare</string>
<key>UIApplicationShortcutItemTitle</key>
<string>表示タイトル2</string>
<key>サブタイトル2</key>
<string>Share an item</string>
</dict>
</array>
####SceneDelegate
アプリが初回起動である場合(タスクキル状態)と、
バックグラウンド状態(すでに起動済みである場合)では
発火する関数が異なります。
//タスクキル状態からクイックアクションを実行した場合
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let shortcutItem = connectionOptions.shortcutItem {
handleShortCutItem(item: shortcutItem)
}
guard let _ = (scene as? UIWindowScene) else { return }
}
//バックグラウンド状態からクイックアクションを実行した場合
func windowScene(_ windowScene: UIWindowScene,
performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void) {
handleShortCutItem(item: shortcutItem)
}
...省略
//Info.plistで設定したUIApplicationShortcutItemTypeを
//ここでハンドリングする
private func handleShortCutItem(item: UIApplicationShortcutItem) {
switch item.type {
case "ショートカットアイテムタイプ2":
print("タイプ2")
case "ショートカットアイテムタイプ1":
print("タイプ1")
default:
break
}
}
##おわりに
いかがでしたでしょうか。
クイックアクションという言葉を知らないとこの手の記事にたどり着くのに
少し時間がかかってしまいますね。