監(jiān)聽還可以發(fā)送信息
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)
}
// 接收通知后的方法回調(diào)
@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) 獲取到通知,用戶數(shù)據(jù)是[\(value1),\(value2)]")
sleep(3)
print("\(name) 執(zhí)行完畢")
}
deinit {
//移除通知監(jiān)聽
NotificationCenter.default.removeObserver(self)
}
}
let observers = [MyObserver(name: "觀察器1"),MyObserver(name: "觀察器2")]
override func viewDidLoad() {
super.viewDidLoad()
print("發(fā)送通知")
let notificationName = Notification.Name(rawValue: "DownloadImageNotification")
// 發(fā)送通知
NotificationCenter.default.post(name: notificationName, object: self,
userInfo: ["value1":"hangge.com", "value2" : 12345])
print("通知完畢")
}