相关链接
直接监控系统方法
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
发送通知
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:
@objc func appStateChange(_ notification: Notification) {
print("********** notification \(String(describing: notification.userInfo!["appState"]!))")
}
deinit {
NotificationCenter.default.removeObserver(self)
}