NSNotificationCenter addObserver in Swift

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

提交回复
热议问题