前言
关于Siri Shortcuts
集成, 网络上资料大多比较有年代感或者杂乱, 接下来做个大致梳理.
根据业务需求不同, 实现方式可以分为在App内执行(需要启动App)和App外部执行(不需要启动App).
同样的, 与之对应的也就有两种方案, NSUserActivity+intent
和intent
.
注意: 适用iOS 12.0及以上版本
(一). Intents扩展文件配置
- 在
TARGETS
中创建一个Intent扩展程序
- 选择激活, 然后在宿主App中生成下面文件
接着在扩展程序文件夹下创建一个Siri意图文件
然后根据需要配置项目Siri的意图
(二). NSUserActivity+intent方式
按方案分析, Siri响应后在App内处理事件; 这种场景的创建也在快捷指令内部添加, 像支付宝的扫一扫
- 首先创建一个依赖App启动响应的自定义意图.
- 当新的意图创建后, 系统会默认在宿主App中的info.plist文件生成相关配置.
- 同时也会生成一个
HBEventIntent.swift
文件, 此文件主要包括下面四个东西.
1 | public class HBEventIntent: INIntent {} |
- 接着我们挨着
IntentHandler.swift
创建自定义意图的处理类HBEventHandler.swift
.
1 | // HBEventHandler.swift |
- 当然,
IntentHandler.swift
入口处代码也必须补充.
1 | // IntentHandler.swift |
- 另外的, 对于此应用内执行方式; 那么接下来就可以在
AppDelegate
中, 添加自定义的相关业务.
1 | // MARK: - Intents |
- 下面即是生成的Siri建议样式, 快捷指令添加如同前面支付宝扫一扫一致.
- 这里有个问题先说明一下, 似乎必须要付费账号才可以在项目接入Siri, 即
Signing &Capablilties
中添加Siri
, 这样就可以通过”嗨, Siri “ 去执行快捷指令. 否则仅能点击快捷触发.
(三). custom intent方式
intent方式常用场景大体都是和宿主内相关业务做一些数据绑定, 然后拿到外部可以独立执行处理事务. 类似的如米家的智能场景绑定执行
- 由于外部执行依赖宿主App 的相关业务数据, 这务必会产生宿主APP和Extension的数据共享问题, 这点后面一段再说. 因业务依赖较重, 接下来做大致介绍.
- 与内部执行方式相同的, 也需要添加处理类. 这里添加
HBSiriHandler
,
1 | // HBSiriHandler.swift |
- 同样的入口方法
handler(for :)
内补充
1 | if intent is HBSiriIntent { |
- 关于指令与业务的绑定, 在宿主App必然会有相关的指令获取, 添加以及更新和删除操作, 这里提供一个自己封装的工具类.
1 | // VoiceShortcutManager.swift |
- 使用场景大致可以如下
1 | /// 若使用PromiseKit, 获取指定intens方式可以如下, |
- 关于如何默认Siri短语; 打开Extension的
Edit Scheme
->Run
->Siri intent Query
, 输入短语即可
- 关于如何Debug调试Extension部分
在前面说的intent中勾选了User confirmation required
, 这个时候当我们点击快捷指令时, 会有弹框提示是否需要运行; 这个时候先不用点执行. 这个时候, 先在Extension中设置断点, 然后进入Xcode
-> Debug
-> Attach to Process
选择与宿主App同级下的intent即可
- 另外在额外补充另一种自定义意图的方法
如图所示, 这种捐赠意图的方式
1 | // 添加时 传入一个自定义意图, 然后进行捐赠, 结果可以接收回调 |
1 | // 使用方式示例 |
注意 此种方式添加后, 在快捷指令 类别及App分栏
内部都可以找到捐赠的意图. 同时需要关注一下入口以及自建处理类.
(四). 宿主APP和Extension的数据共享
这里介绍下App Groups
.
比如 宿主App添加了一个App Groups
, 设定为 group.com.hb.hbswiftkit.hbintent
, 那么与之共享数据的Extension也必须勾选此App Groups
使用方式 UserDefaults(suiteName:)
如下.
1 | // MARK: 项目内标识信息 |
(五). 带Extension的应用CocoaPods如何配置
- 如果是宿主App和Extension为同平台下共享部分三方库
1 | platform :ios,'10.0' |
- 如果是不同平台下共享部分三方库
1 | use_frameworks! |
相关文件补充 HBSwiftKit_Example -> shortcuts
(六). 参考
iOS Siri Shortcuts 集成初探 (Objective-C)
SiriKit框架详细解析(七) —— 构建Siri Shortcuts简单示例(一)
iOS开发之App Extension(应用扩展)之 – Today Extension
- 本文作者: 醉疏狂
- 本文链接: https://hubin97.github.io/2022/07/08/Siri快捷指令/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!