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

Swift5中如何处理点击本地通知返回iOS应用的事件?

iOS后台本地通知点击事件的处理方案

一、能否通过UIApplication的标准方法,用NotificationCenter订阅特定触发事件?

不能直接实现。UIApplication提供的系统通知(如UIApplication.willEnterForegroundNotification)无法区分应用是通过点击本地通知还是用户手动打开回到前台的,因此无法精准订阅“点击后台本地通知带回前台”这个特定场景的触发事件。

二、Swift5中处理用户点击本地通知的最佳方式(前台ViewController处理)

苹果在iOS 10及以上推荐使用UserNotifications框架处理通知逻辑,核心是通过UNUserNotificationCenterDelegate捕获通知点击事件,再将事件传递到前台ViewController。具体步骤如下:

1. 配置通知权限与代理

在AppDelegate(iOS 12及以下)或SceneDelegate(iOS 13+)中完成初始化:

// AppDelegate.swift 示例
import UserNotifications

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 设置通知中心代理
        UNUserNotificationCenter.current().delegate = self
        
        // 请求通知权限(按需设置权限类型)
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { granted, error in
            if let error = error {
                print("通知权限请求失败:\(error.localizedDescription)")
            }
        }
        
        // 处理应用从完全关闭状态点击通知启动的情况
        if let notificationResponse = launchOptions?[.localNotification] as? UILocalNotification {
            self.handleNotificationTap(userInfo: notificationResponse.userInfo)
        }
        
        return true
    }
    
    // MARK: - UNUserNotificationCenterDelegate
    // 用户点击通知时触发(应用在后台/前台均会调用)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        // 可通过userInfo中的自定义标识,判断是否为目标通知
        if let notifyType = userInfo["targetNotificationType"] as? String, notifyType == "backgroundTriggered" {
            handleNotificationTap(userInfo: userInfo)
        }
        completionHandler()
    }
    
    // 统一处理通知点击逻辑,转发到前台VC
    private func handleNotificationTap(userInfo: [AnyHashable: Any]?) {
        NotificationCenter.default.post(
            name: NSNotification.Name(rawValue: "DidTapBackgroundLocalNotification"),
            object: userInfo
        )
    }
}

2. 前台ViewController订阅并处理事件

在需要处理通知的ViewController中,订阅自定义通知并实现处理逻辑:

class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 订阅自定义通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(onNotificationTapped(_:)),
            name: NSNotification.Name(rawValue: "DidTapBackgroundLocalNotification"),
            object: nil
        )
    }
    
    @objc private func onNotificationTapped(_ notification: Notification) {
        guard let userInfo = notification.object as? [AnyHashable: Any],
              let message = userInfo["contentMessage"] as? String else {
            return
        }
        // 这里实现具体业务逻辑,比如弹窗提示、页面跳转等
        let alert = UIAlertController(title: "收到通知", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确认", style: .default))
        present(alert, animated: true)
    }
    
    deinit {
        // 移除通知监听,避免内存泄漏
        NotificationCenter.default.removeObserver(self)
    }
}

关键注意事项

  • 区分通知类型:在本地通知的userInfo中添加自定义标识(如示例中的targetNotificationType),可以精准处理特定路径触发的通知。
  • 应用启动场景:不要忽略应用从完全关闭状态点击通知启动的情况,需在启动方法中解析launchOptions并触发处理逻辑。
  • 内存泄漏防护:务必在ViewController销毁时移除通知监听,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:35:33