相关链接
直接监控系统方法
var backgroundObserver :NSObjectProtocol?
// object必须是nil,否则貌似没反应
backgroundObserver = NoticeCenter.addObserver(forName: NSNotification.Name.UIApplicationDidEnterBackground, object: nil, queue: OperationQueue.main) { (notification) in
print("******** 程序进入后台")
}
deinit {
// 移除通知
NoticeCenter.removeObserver(backgroundObserver!)
}
自定义方法
获取全局通知方法
let NoticeCenter = NotificationCenter.default // 获取NotificationCenter
发送通知
NoticeCenter.post(name: NSNotification.Name(rawValue: "WebMusicState"), object: self, userInfo: ["appState":"applicationWillEnterForeground"])
注册通知
使用block方法
var WebMusicStateObserver :NSObjectProtocol?
// 注册通知
WebMusicStateObserver = NoticeCenter.addObserver(forName: NSNotification.Name(rawValue: "WebMusicState"), object: nil, queue: OperationQueue.main) { (notification) in
print("********** notification \(String(describing: notification.userInfo!["appState"]!))")
}
deinit {
// 移除通知
NoticeCenter.removeObserver(WebMusicStateObserver!)
}
使用selector方法
// 注册通知
NoticeCenter.addObserver(self, selector: #selector(appStateChange(_:)), name: NSNotification.Name(rawValue: "WebMusicState"), object: nil)
// 调取的方法
@objc func appStateChange(_ notification: Notification) {
print("********** notification \(String(describing: notification.userInfo!["appState"]!))")
}
deinit {
//移除通知监听
NotificationCenter.default.removeObserver(self)
}