监听还可以发送信息
class MyObserver {
var name:String = ""
init(name:String){
self.name = name
// 定义 通知名
let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
// 自定义一个通知
NotificationCenter.default.addObserver(self,
selector:#selector(downloadImage(notification:)),
name: notificationName, object: nil)
}
// 接收通知后的方法回调
@objc func downloadImage(notification: Notification) {
let userInfo = notification.userInfo as! [String: AnyObject]
let value1 = userInfo["value1"] as! String
let value2 = userInfo["value2"] as! Int
print("\(name) 获取到通知,用户数据是[\(value1),\(value2)]")
sleep(3)
print("\(name) 执行完毕")
}
deinit {
//移除通知监听
NotificationCenter.default.removeObserver(self)
}
}
let observers = [MyObserver(name: "观察器1"),MyObserver(name: "观察器2")]
override func viewDidLoad() {
super.viewDidLoad()
print("发送通知")
let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
// 发送通知
NotificationCenter.default.post(name: notificationName, object: self,
userInfo: ["value1":"hangge.com", "value2" : 12345])
print("通知完毕")
}