如何在Swift中运行Shortcuts App里的「Open App」操作?
在Swift中调用Shortcuts的「Open App」操作
方式一:直接实现打开App的功能(替代Shortcuts操作)
如果你的需求只是打开指定App,无需依赖Shortcuts,直接调用系统API即可:
- 先确认目标App的URL Scheme(比如微信是
weixin://),并在项目的Info.plist中添加LSApplicationQueriesSchemes数组,将目标Scheme加入白名单,否则无法检测App是否安装。 - 调用
UIApplication的打开方法:
import UIKit func openTargetApp(with scheme: String) { guard let appURL = URL(string: scheme) else { return } if UIApplication.shared.canOpenURL(appURL) { UIApplication.shared.open(appURL, options: [:]) { success in if !success { print("打开目标App失败") } } } else { print("目标App未安装或Scheme未配置") } } // 调用示例:打开微信 openTargetApp(with: "weixin://")
方式二:触发包含「Open App」操作的Shortcuts快捷指令
如果确实需要调用Shortcuts内置的「Open App」操作,需先创建对应快捷指令再触发:
- 在Shortcuts App中新建快捷指令,添加「Open App」操作并选择目标App,保存后命名(比如“打开指定App”)。
- 长按该快捷指令,选择「分享」-「复制链接」,得到类似
shortcuts://run-shortcut?name=打开指定App的URL。 - 在Swift代码中触发该URL:
import UIKit func triggerShortcutOpenApp() { guard let shortcutURL = URL(string: "shortcuts://run-shortcut?name=打开指定App") else { return } if UIApplication.shared.canOpenURL(shortcutURL) { UIApplication.shared.open(shortcutURL, options: [:]) { success in if !success { print("触发快捷指令失败") } } } else { print("未安装Shortcuts App") } } // 调用示例 triggerShortcutOpenApp()
关于AppIntents的说明
AppIntents是用来让你的App向Shortcuts提供自定义操作的框架,和调用Shortcuts内置的「Open App」操作是两个方向——前者是让Shortcuts调用你的App功能,后者是你的App调用Shortcuts的操作,无需用AppIntents实现后者需求。
内容的提问来源于stack exchange,提问作者Ezra Magaram
相关产品推荐
相关产品推荐

