Work With NSNotification Center In Swift Ios

 
NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "batteryLevelChanged:",
    name: UIDeviceBatteryLevelDidChangeNotification,
    object: nil)
 
 
@objc func batteryLevelChanged(notification: NSNotification){     
    //do stuff
} 


=========================================
Send(Post)
NSNotificationCenter.defaultCenter().postNotificationName 
("NotificationIdentifier", object: nil)
 

Receive(Get) Notification 
 
NSNotificationCenter.defaultCenter().addObserver(self, selector: 
 "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil) 


Remove Notification

NSNotificationCenter.defaultCenter().removeObserver
 (self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver 
(self) // Remove from all notifications being observed
 
 
Method handler for received Notification

func methodOfReceivedNotification(notification: NSNotification){
    //Take Action on Notification
}
 
Annotate either the class or the target method with @objc
 
@objc private func methodOfReceivedNotification(notification: NSNotification){
    //Take Action on Notification
}

//Or

dynamic private func methodOfReceivedNotification(notification: NSNotification){
    //Take Action on Notification
}  

Popular posts from this blog

How to Use pagination ScrollView in Swift

UISearchBar search text color , background color swift 3

How To Add Multiple Line in Lable in Swift Ios