问题

如何在Swift中将观察者添加到默认通知中心?我正在尝试端口在电池级别更改时发送通知的这行代码.

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
 

  最佳答案

它与Objective-C API相同,但使用Swift的语法.

 NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: #selector(batteryLevelChanged:),
    name: UIDeviceBatteryLevelDidChangeNotification,
    object: nil)
 

Swift 3:

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

Swift 4.2& Swift 5:

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

如果您的观察者不从 Objective-C 对象继承,您必须用 @objc 前缀您的方法,以便将其用作选择器。

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

NSNotificationCenter Class Reference , Interaction with Objective-C API

  相同标签的其他问题

iosswiftnsnotificationcenter