NSNotificationCenter addObserver in Swift

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

    In swift 3, Xcode 8.2:- checking battery state level

    //Add observer
    NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
    
    
     //Fired when battery level changes
    
     func batteryStateDidChange(notification: NSNotification){
            //perform manipulation here
        }
    
    0 讨论(0)
  • 2020-11-22 06:14

    It's the same as the Objective-C API, but uses Swift's syntax.

    Swift 4.2 & Swift 5:

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(self.batteryLevelChanged),
        name: UIDevice.batteryLevelDidChangeNotification,
        object: nil)
    

    If your observer does not inherit from an Objective-C object, you must prefix your method with @objc in order to use it as a selector.

    @objc private func batteryLevelChanged(notification: NSNotification){     
        //do stuff using the userInfo property of the notification object
    }
    

    See NSNotificationCenter Class Reference, Interacting with Objective-C APIs

    0 讨论(0)
  • 2020-11-22 06:14

    We should remove notification also.

    Ex.

    deinit 
    {
      NotificationCenter.default.removeObserver(self, name:NSNotification.Name(rawValue: "notify"), object: nil)
    
    }
    
    0 讨论(0)
  • 2020-11-22 06:14

    NSNotificationCenter add observer syntax in Swift 4.0 for iOS 11

      NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    

    This is for keyboardWillShow notification name type. Other type can be selected from the available option

    the Selector is of type @objc func which handle how the keyboard will show ( this is your user function )

    0 讨论(0)
  • 2020-11-22 06:17

    Swift 5 Notification Observer

    override func viewDidLoad() {
        super.viewDidLoad() 
        NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
    }
    
    @objc func batteryLevelChanged(notification : NSNotification){
        //do here code
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: nil)
    
    }
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题