NSNotificationCenter addObserver in Swift

后端 未结 14 2301
难免孤独
难免孤独 2020-11-22 05:23

How do you add an observer in Swift to the default notification center? I\'m trying to port this line of code that sends a notification when the battery level changes.

14条回答
  •  执笔经年
    2020-11-22 06:29

    In Swift 5

    Let's say if want to Receive Data from ViewControllerB to ViewControllerA

    ViewControllerA (Receiver)

    import UIKit
    
    class ViewControllerA: UIViewController  {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //MARK: - - - - - Code for Passing Data through Notification Observer - - - - -
            // add observer in controller(s) where you want to receive data
            NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
        }
    
        //MARK: - - - - - Method for receiving Data through Post Notificaiton - - - - -
        @objc func methodOfReceivedNotification(notification: Notification) {
            print("Value of notification : ", notification.object ?? "")
        }
    }
    

    ViewControllerB (Sender)

    import UIKit
    
    class ViewControllerB: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //MARK: - - - - - Set data for Passing Data Post Notification - - - - -
            let objToBeSent = "Test Message from Notification"
            NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: objToBeSent)
        }
    
    }
    

提交回复
热议问题