Swift如何通过推送或应用内打开「搜索小组件」视图?
实现通过应用内操作或推送打开小组件搜索视图的方法
一、应用内弹窗触发
直接调用iOS系统提供的小组件库URL Scheme,在弹窗的确认操作中执行打开逻辑即可:
先在
Info.plist中添加URL Scheme白名单,避免canOpenURL返回false:<key>LSApplicationQueriesSchemes</key> <array> <string>x-apple-widgets</string> </array>在弹窗按钮点击事件中打开小组件搜索视图:
// 创建弹窗 let widgetAlert = UIAlertController(title: "打开小组件", message: "点击确认进入小组件搜索视图", preferredStyle: .alert) // 确认按钮逻辑 widgetAlert.addAction(UIAlertAction(title: "确认", style: .default) { _ in guard let widgetURL = URL(string: "x-apple-widgets://") else { return } if UIApplication.shared.canOpenURL(widgetURL) { UIApplication.shared.open(widgetURL, options: [:], completionHandler: nil) } }) widgetAlert.addAction(UIAlertAction(title: "取消", style: .cancel)) present(widgetAlert, animated: true)
二、推送通知触发
通过推送通知的自定义字段携带小组件URL,用户点击推送时触发打开操作:
推送Payload示例(包含自定义跳转字段):
{ "aps": { "alert": { "title": "查看你的小组件", "body": "点击打开小组件搜索视图" }, "sound": "default" }, "widget_launch_url": "x-apple-widgets://" }在通知接收回调中处理跳转逻辑(以SceneDelegate为例):
import UserNotifications func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let notificationContent = response.notification.request.content // 提取自定义字段中的URL if let urlString = notificationContent.userInfo["widget_launch_url"] as? String, let targetURL = URL(string: urlString) { if UIApplication.shared.canOpenURL(targetURL) { UIApplication.shared.open(targetURL, options: [:], completionHandler: nil) } } completionHandler() }
注意事项
- 该方案仅支持iOS 14及以上版本(Widget Extension最低兼容版本为iOS14)
- 确保应用已获得用户的通知权限(推送触发场景)
内容的提问来源于stack exchange,提问作者oguzizmir
相关产品推荐
相关产品推荐

