基于Siri Shortcuts与App Intents实现App功能语音控制的技术咨询
嘿,我来给你梳理下具体的实现方向,你要的正是App Intents的核心场景——不需要依赖Shortcuts App,就能让Siri直接触发你App内的地图缩放功能,步骤很清晰:
创建自定义Intent类型
你需要在项目里新建继承自AppIntent的结构体,比如分别做ZoomInMapIntent和ZoomOutMapIntent(对应你两个语音指令)。每个Intent要配置好基础信息,还要在perform()方法里写触发后的逻辑。举个例子:import AppIntents struct ZoomInMapIntent: AppIntent { static let title: LocalizedStringResource = "Zoom In Map" static let description = IntentDescription("Zooms in the map in your app") static var openAppWhenRun: Bool = true // 触发时打开App(如果不在前台) func perform() async throws -> some IntentResult { // 这里传递触发信号给你的地图模块,比如用通知 NotificationCenter.default.post(name: NSNotification.Name("ZoomInMap"), object: nil) return .result() } }同理再写一个
ZoomOutMapIntent,把通知名称改成ZoomOutMap就行。配置App权限与Intent优化
首先在Xcode项目的Capabilities里开启“Siri”权限,系统会自动帮你处理Info.plist的相关配置。另外可以给Intent加上搜索关键词,帮助Siri更精准匹配你的语音指令:static let description = IntentDescription( "Zooms in the map in your app", category: .app, searchKeywords: ["zoom", "map", "in"] )这样Siri听到“Zoom in map”时,更容易关联到你的Intent。
关联App内的地图缩放逻辑
刚才在Intent的perform()里用了通知来传递信号,你可以在地图所在的ViewController里监听这个通知,执行实际的缩放操作:class MapViewController: UIViewController { // 假设你有一个地图视图实例 @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(handleZoomIn), name: NSNotification.Name("ZoomInMap"), object: nil) // 同理添加ZoomOut的监听 NotificationCenter.default.addObserver(self, selector: #selector(handleZoomOut), name: NSNotification.Name("ZoomOutMap"), object: nil) } @objc private func handleZoomIn() { // 替换成你实际的地图缩放代码,比如调整地图级别 let newZoomLevel = mapView.camera.altitude * 0.5 mapView.camera.altitude = newZoomLevel } @objc private func handleZoomOut() { let newZoomLevel = mapView.camera.altitude * 2 mapView.camera.altitude = newZoomLevel } }除了通知,你也可以用Combine、单例引用等方式传递触发信号,只要能把Intent的触发和你的地图功能关联起来就行。
测试验证
运行App后回到主屏幕,喊“Hey Siri, Zoom in map”,系统会弹出授权请求,同意之后就能直接触发你的地图缩放功能了。如果Siri没匹配到指令,可以试着调整Intent的标题或关键词,或者用更贴近配置的语音表述。
完全不用和Shortcuts App打交道,App Intents就是专门做这种“直接用Siri触发App内功能”的场景,用户不需要创建或共享任何快捷方式,直接语音调用就行。
备注:内容来源于stack exchange,提问作者Nic Hubbard

