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

iOS 17 Live Activity按钮调用RN函数并唤起RN应用的实现方案

问题描述

我使用iOS 17与React Native开发,已通过LiveActivityIntent和NotificationCenter实现从iOS Live Activity按钮小组件调用RN函数,但点击按钮时仅执行函数,无法唤起应用至前台。希望实现点击按钮时同时调用RN函数并唤起应用,模仿Live Activity默认的点击行为,求具体实现方法。

当前使用的Swift代码如下:

@available(iOS 17.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *)
struct SuperCharge: LiveActivityIntent {
    
    static var title: LocalizedStringResource = "Emoji Ranger SuperCharger"
    static var description = IntentDescription("All heroes get instant 100% health.")
    
    func perform() async throws -> some IntentResult {
        print("calling function from Swift!!!!!")
        
        NotificationCenter.default.post( name: Notification.Name("InvokeEvent"),
                                         object: nil,
                                         userInfo: ["message": "Hello from Widget"]
        )
        return .result()
    }
}

我查阅过Apple官方的「从小组件或Live Activity链接到特定应用场景」相关文档,但未找到对应答案或示例。

实现方法

要实现点击按钮时同时唤起应用,只需在perform()方法中添加唤起应用的逻辑,具体步骤如下:

  1. 首先确保导入UIKit框架(若未导入)
  2. 在perform()方法内,使用UIApplication.shared.open()方法唤起应用,需搭配应用的自定义URL Scheme。

修改后的完整代码示例:

import UIKit

@available(iOS 17.0, macOS 13.0, watchOS 9.0, tvOS 16.0, *)
struct SuperCharge: LiveActivityIntent {
    
    static var title: LocalizedStringResource = "Emoji Ranger SuperCharger"
    static var description = IntentDescription("All heroes get instant 100% health.")
    
    func perform() async throws -> some IntentResult {
        print("calling function from Swift!!!!!")
        
        // 保留原有调用RN函数的通知逻辑
        NotificationCenter.default.post( name: Notification.Name("InvokeEvent"),
                                         object: nil,
                                         userInfo: ["message": "Hello from Widget"]
        )
        
        // 新增唤起应用的逻辑,替换为你自己的App URL Scheme
        if let appUrl = URL(string: "your-app-scheme://") {
            await UIApplication.shared.open(appUrl)
        }
        
        return .result()
    }
}

关键注意事项

  • 配置URL Scheme:必须先在Xcode项目中为React Native应用设置自定义URL Scheme:
    • 打开项目的Info.plist文件
    • 添加URL types数组,新增一项并设置URL Schemes为自定义值(比如your-app-scheme)
  • 异步调用:open()方法为异步方法,需添加await关键字确保唤起操作完成后再返回结果。

如果需要跳转到应用内特定页面,可以在URL Scheme中携带参数(如your-app-scheme://home),然后在React Native端通过Linking模块监听并处理该链接。

内容的提问来源于stack exchange,提问作者Roman S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 13:12:55