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

}

}

你可能感兴趣的:(Swift 3 之NotificationCenter)