You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift如何通过推送或应用内打开「搜索小组件」视图?

实现通过应用内操作或推送打开小组件搜索视图的方法

一、应用内弹窗触发

直接调用iOS系统提供的小组件库URL Scheme,在弹窗的确认操作中执行打开逻辑即可:

  1. 先在Info.plist中添加URL Scheme白名单,避免canOpenURL返回false:

    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>x-apple-widgets</string>
    </array>
    
  2. 在弹窗按钮点击事件中打开小组件搜索视图:

    // 创建弹窗
    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,用户点击推送时触发打开操作:

  1. 推送Payload示例(包含自定义跳转字段):

    {
        "aps": {
            "alert": {
                "title": "查看你的小组件",
                "body": "点击打开小组件搜索视图"
            },
            "sound": "default"
        },
        "widget_launch_url": "x-apple-widgets://"
    }
    
  2. 在通知接收回调中处理跳转逻辑(以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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:37:17