Swift 3 之NotificationCenter

Example to define your custom Notification name:


extension Notification.Name {

static let BluetoothStatusChangeNotification = Notification.Name("BluetoothStatusChangedNotification")

static let BeaconStatusStartNotification = Notification.Name("BeaconStatusStartNotification")

static let BeaconStatusStopNotification = Notification.Name("BeaconStatusStopNotification")}

Example to show how to post a notification with parameter.

let bluetoothStatus = "your bluetooth status."//monitor the status with the specific callback.

NotificationCenter.default.post(name: .BluetoothStatusChangeNotification, object: bluetoothStatus) 

Example of useage

override func viewWillAppear(_ animated: Bool) {

super.viewWillAppear(animated)

//Check Bluetooth Status First if on (online and AR) else off (offline and AR)

NotificationCenter.default.addObserver(self, selector: #selector(self.bluetoothStatusChanged(notification:)), name: .BluetoothStatusChangeNotification, object: nil)

}

override func viewWillDisappear(_ animated: Bool) {

super.viewWillDisappear(animated)

NotificationCenter.default.removeObserver(self, name: .BluetoothStatusChangeNotification, object: nil)

}


Example of received method 

func bluetoothStatusChanged(notification:Notification){

if let status = notification.object as? Bool {

//Your logic

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容