SwiftNotification
针对 NotificationCenter 缺陷而设计的工具,NotificationCenter 需要监听移除,添加次数等。
为 NSObject 扩展一个属性:notifiCenter,继承自 NSObject 的类都可以方便地使用它收发通知,无需关心通知移除,deinit 会自动移除,并防止多次添加同一个通知(只有最后一个生效)
安装
Cocoapods
1. 在 Podfile 中添加 pod ‘Swift_Notification’
2. 执行 pod install 或 pod update
3. 导入 import Swift_Notification
Swift Package Manager
从 Xcode 11 开始,集成了 Swift Package Manager,使用起来非常方便。SwiftNotification 也支持通过 Swift Package Manager 集成。
在 Xcode 的菜单栏中选择 File > Swift Packages > Add Package Dependency
,然后在搜索栏输入
https://github.com/jackiehu/SwiftNotification
,即可完成集成。
手动集成
SwiftNotification 也支持手动集成,只需将 Sources 文件夹中的 SwiftNotification 文件夹拖到需要集成的项目即可
使用
发送通知
notifiCenter.postNotification("notiName", object: "cccccc", userInfo: ["key":"cccccc"])
接收通知
notifiCenter.addNotification("notiName", callBack: { (noti) in
print("\(String(describing: noti.object)) -- \(String(describing: noti.userInfo))")
})
系统通知
notifiCenter.addNotification(UIApplication.willEnterForegroundNotification, callBack: { (noti) in
print("1111111-- \(String(describing: noti.userInfo))")
})
API
/// 移除所有通知
public func removeAllNotification()
/// 移除单个通知
/// - Parameter name: 通知名称String
public func removeNotification(name : String)
/// 移除单个系统通知
/// - Parameter forName: NSNotification.Name通知名称
public func removeNotification(notiName : NSNotification.Name)
/// 移除多个通知
/// - Parameter names: 通知名称String数组
public func removeNotifications(names : [String])
/// 移除多个系统通知
/// - Parameter notiNames: 通知名称NSNotification.Name数组
public func removeNotifications(notiNames : [NSNotification.Name])
/// 注册添加通知
/// - Parameters:
/// - name: 通知名称String
/// - callBack: 通知执行的回调
public func addNotification(_ name : String, callBack : @escaping (Notification) -> Void)
/// 注册添加多个通知
/// - Parameters:
/// - names: 通知名称String数组
/// - callBack: 通知执行的回调
public func addNotifications(_ names : [String], callBack : @escaping (Notification) -> Void)
/// 注册添加通知
/// - Parameters:
/// - notiName: NSNotification.Name通知名称
/// - callBack: 通知执行的回调
public func addNotification(_ notiName : NSNotification.Name, callBack : @escaping (Notification) -> Void)
/// 注册添加多个通知
/// - Parameters:
/// - notiNames: NSNotification.Name通知名称数组
/// - callBack: 通知执行的回调
public func addNotifications(_ notiNames : [NSNotification.Name], callBack : @escaping (Notification) -> Void)
/// 发送通知
/// - Parameters:
/// - name: 通知名称
/// - object: 发送对象
/// - userInfo: 发送字典
public func postNotification(_ name : String, object: Any? = nil, userInfo : [String : Any]? = nil)
详细用法参见Demo PushViewController