SwiftUI中如何在通知发送时触发指定函数?
在iOS通知触发时自动执行自定义函数的实现方案
针对你的需求,分几种场景给出具体实现方式:
1. App前台运行时,通知触发即执行函数
当App在前台收到通知时,系统会调用UNUserNotificationCenterDelegate的willPresent方法,你可以在这里直接执行自定义函数:
第一步:设置通知中心代理
在AppDelegate(iOS 12及以下)或SceneDelegate(iOS 13+)的初始化方法里设置代理:
// AppDelegate示例 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UNUserNotificationCenter.current().delegate = self return true } // SceneDelegate示例 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { UNUserNotificationCenter.current().delegate = self }
第二步:实现代理方法执行自定义函数
扩展对应的Delegate类,添加代理方法:
// AppDelegate扩展 extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 调用你的自定义函数 yourCustomFunction() // 配置前台通知的展示方式(比如弹窗+声音) completionHandler([.alert, .sound]) } } // SceneDelegate扩展 extension SceneDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { yourCustomFunction() completionHandler([.alert, .sound]) } }
2. 用户点击通知时执行函数(无论App状态)
如果需要在用户点击通知的时候执行函数,实现didReceiveNotificationResponse代理方法:
// 以AppDelegate为例,SceneDelegate同理 extension AppDelegate: UNUserNotificationCenterDelegate { // ... 上面的willPresent方法 ... func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { yourCustomFunction() // 必须调用completionHandler结束处理 completionHandler() } }
3. App后台/未运行时,通知触发静默执行函数
如果需要在通知触发时(无论用户是否点击),即使App在后台也执行代码,需要使用UNNotificationServiceExtension(这是一个独立的扩展进程,最多有30秒执行时间):
第一步:创建Notification Service Extension
在Xcode中,依次点击File -> New -> Target,选择Notification Service Extension,按照提示完成创建。
第二步:在扩展中执行自定义函数
打开生成的NotificationService.swift,修改didReceive方法:
class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) // 在这里执行你的自定义函数 yourCustomFunction() // 必须传递处理后的通知内容,即使没有修改也要调用 if let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // 执行时间到期时,必须调用contentHandler if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } }
⚠️ 注意:Extension是独立进程,无法直接访问App主进程的变量或方法,如果你需要共享数据,需要配置App Groups来实现跨进程数据共享。
内容的提问来源于stack exchange,提问作者Cian B
相关产品推荐
相关产品推荐

