Swift 的一种新的先进的通知中心
CocoaPods
之前
pod 'SwiftyNotification'
观察者
NSNotificationName
让我疯狂。太麻烦了。
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "SomeChange"), object: nil, queue: nil) { (noti) in
guard let info = noti.userInfo else { return }
// info["Some hard to remember key"] ....
// What's the type I need ?
}
关于 userinfo
的内容是什么,什么是我想要的?这将花费你很多时间。
发布通知者
当你想要发布一个通知时,你必须搜索通知的 NotificationName
。然后,你必须找到对应的 userinfo
的 Key。
NotificationCenter.default.post(name: NSNotification.Name("SomeChange"), object: nil, userInfo: ["What's the key": someValue])
我想简单点
现在
您只需为其中一个通知创建一个 struct。
您可以使用协议帮助分配通知的 userinfo 类型。
您不再需要猜测通知中的信息
一眼看去,通知信息需要 name
和 age
struct MarketChangeNoti: INewNotifioncation {
typealias InfoType = (name: String, age: Int)
static var name: String = "marketChangeNoti"
}
NSNotificationName
让我疯狂。太麻烦了。
NewNotifications.MarketChangeNoti.addObserve(notiDispose, response: ((name: String, age: Int)) -> ())
// info's type is a Tuple which contain String and Int, we also know the meaning of info
MarketChangeNoti.addObserve(notiDispose) { (result) in
print(result.name, "3232" , result.age)
}
当你想要发布一个通知时,你必须搜索通知的 NotificationName
。然后,你必须找到对应的 userinfo
的 Key。
NewNotifications.MarketChangeNoti.post(info: (name: String, age: Int)
移除通知
或
var notiDispose = NewNotiDispose()
NewNotifications.MarketChangeNoti.addObserve(notiDispose)
Dimitris Koutsogiorgas、Danielle Lancashire、Eric Amorde、Orta Therox、Paul Beusterien、Samuel Giddins 及 CocoaPods 开发团队 的贡献,CocoaPods 项目来自
NewNotifications.MarketChangeNoti.addObserve(.always)