Friday, August 10, 2018

Swift 3.0  Post Local Notification

Notification name should be same for both sender and receiver

// Some where in class A [Post (Broadcast)]

let notificationObjName = Notification.Name("NotificationName")
NotificationCenter.default.post(name: notificationObjName, object: nil)


// And in other class B register for notification

let notificationName = Notification.Name("NotificationName")
NotificationCenter.default.addObserver(self, selector: #selector(ClassB.methodName), name: notificationName, object: nil)

// This method is call when post notification in Class B
func methodName(notification: NSNotification) {
        // Do, what you want
    }



Pass data using notification

let tempDict:[String: UIImage] = ["image": image]

// post a notification with data to class A
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: tempDict)
        
// Register to receive notification in your class B
NotificationCenter.default.addObserver(self, selector: #selector(classB.methodName(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// recive notification
func methodName(_ notify: NSNotification) {        
    if let image = notify.userInfo?["image"] as? UIImage {
       // Do, what you want
     }
}










No comments:

Post a Comment