NSNotificationCenter addObserver in Swift

后端 未结 14 2305
难免孤独
难免孤独 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:21

    1. Declare a notification name

      extension Notification.Name {
          static let purchaseDidFinish = Notification.Name("purchaseDidFinish")
      }
      
    2. You can add observer in two ways:

      Using Selector

      NotificationCenter.default.addObserver(self, selector: #selector(myFunction), name: .purchaseDidFinish, object: nil)
      
      @objc func myFunction(notification: Notification) {
          print(notification.object ?? "") //myObject
          print(notification.userInfo ?? "") //[AnyHashable("key"): "Value"]
      }
      

      or using block

      NotificationCenter.default.addObserver(forName: .purchaseDidFinish, object: nil, queue: nil) { [weak self] (notification) in
          guard let strongSelf = self else {
              return
          }
      
          strongSelf.myFunction(notification: notification)
      }
      
      func myFunction(notification: Notification) {
          print(notification.object ?? "") //myObject
          print(notification.userInfo ?? "") //[AnyHashable("key"): "Value"]
      }
      
    3. Post your notification

      NotificationCenter.default.post(name: .purchaseDidFinish, object: "myObject", userInfo: ["key": "Value"])
      

    from iOS 9 and OS X 10.11. It is no longer necessary for an NSNotificationCenter observer to un-register itself when being deallocated. more info

    For a block based implementation you need to do a weak-strong dance if you want to use self inside the block. more info

    Block based observers need to be removed more info

    let center = NSNotificationCenter.defaultCenter()
    center.removeObserver(self.localeChangeObserver)
    

提交回复
热议问题