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

如何在SwiftUI中打印NotificationCenter的所有通知?

调试时捕获并打印所有NotificationCenter通知的实用方案

日常调试过程中,能把NotificationCenter发出的所有通知都输出到控制台,对排查事件传递类问题帮助很大。我找了一圈没看到现成的分享,这里把自己的实现方法整理出来。

实现思路

通过方法交换(Method Swizzling)替换NotificationCenter的通知发布方法,在原逻辑执行前插入日志打印代码,以此捕获所有发出的通知信息。

Swift 实现代码

import Foundation

extension NotificationCenter {
    static func enableDebugLogging() {
        // 适配iOS版本,避免方法签名变更导致异常
        guard !ProcessInfo.processInfo.isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: 16, minorVersion: 0, patchVersion: 0)) else {
            print("⚠️ iOS 16+ 需额外适配异步post方法")
            return
        }
        
        let originalSelector = #selector(post(name:object:userInfo:))
        let swizzledSelector = #selector(swizzled_post(name:object:userInfo:))
        
        guard let originalMethod = class_getInstanceMethod(self, originalSelector),
              let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else {
            return
        }
        
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
    
    @objc private func swizzled_post(name: NSNotification.Name, object: Any?, userInfo: [AnyHashable : Any]?) {
        // 打印通知详情
        print("📢 通知已发布:")
        print("名称: \(name.rawValue)")
        if let obj = object {
            print("关联对象: \(obj)")
        }
        if let info = userInfo {
            print("附加信息: \(info)")
        }
        print("------------------------")
        
        // 调用原发布逻辑
        swizzled_post(name: name, object: object, userInfo: userInfo)
    }
}

使用方式

在App启动代码中(比如AppDelegate或SceneDelegate的初始化方法里)仅Debug模式下开启:

#if DEBUG
NotificationCenter.enableDebugLogging()
#endif

注意事项

  • 仅在Debug环境下启用,避免拖慢正式包性能
  • iOS 16及以上新增了异步发布通知的方法,需要额外适配对应方法的交换逻辑
  • 确保方法交换只执行一次,可通过添加标识位避免重复交换引发逻辑异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:56:06