如何在默认的通知中心中添加一个观察者?我试图移植这行代码,当电池电量变化时发送通知。

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

当前回答

创建一个objc函数,当通知被调用时执行该函数。

 @objc func reloadNotification(_ notification: Notification) {
        tblview.reloadData()
    }

在didload视图中添加通知观察者。

  NotificationCenter.default.addObserver(self, selector:#selector(reloadNotification(_:)), name: Notification.Name("reloadSideMenuDataNS"),object: nil) 

将通知发布到想要调用函数的位置。

 NotificationCenter.default.post(name: Notification.Name("reloadSideMenuDataNS"), object: nil) 

您可以删除您的通知在视图已消失下面。

 NotificationCenter.default.removeObserver(self, name: Notification.Name("reloadSideMenuDataNS"), object: nil)

其他回答

创建一个objc函数,当通知被调用时执行该函数。

 @objc func reloadNotification(_ notification: Notification) {
        tblview.reloadData()
    }

在didload视图中添加通知观察者。

  NotificationCenter.default.addObserver(self, selector:#selector(reloadNotification(_:)), name: Notification.Name("reloadSideMenuDataNS"),object: nil) 

将通知发布到想要调用函数的位置。

 NotificationCenter.default.post(name: Notification.Name("reloadSideMenuDataNS"), object: nil) 

您可以删除您的通知在视图已消失下面。

 NotificationCenter.default.removeObserver(self, name: Notification.Name("reloadSideMenuDataNS"), object: nil)

在Swift 5中

我们说如果想从ViewControllerB接收数据到 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 ?? "")
    }
}

视图控制器 B (发射器)

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)
    }

}

使用NSNotificationCenter传递数据

也支持通过swift 3.0中的NotificationCentre和swift 2.0中的NSNotificationCenter进行数据传递。

Swift 2.0版本

使用userInfo传递信息,userInfo是一个可选的字典类型[NSObject: AnyObject]?

let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
 NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// Register to receive notification in your class
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// handle notification
func showSpinningWheel(notification: NSNotification) {
  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
}

Swift 3.0版本

userInfo现在需要[AnyHashable:Any]?作为一个参数,我们在Swift中作为字典字面量提供

let imageDataDict:[String: UIImage] = ["image": image]

// post a notification
 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
// `default` is now a property, not a method call

// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// handle notification
func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
}

使用NotificationCentre(swift 3.0)和NSNotificationCenter(swift 2.0)传递源数据

这是一个非常简单的自定义通知观察者和post的例子

添加通知观察员

NotificationCenter.default.addObserver(self, selector: #selector(myFunction), name: Notification.Name("CustomeNotificationName"), object: nil)

添加选择器并处理观察者调用

@objc func myFunction(notification: Notification) {
    
    //Write you code
}

在需要时发布通知(观察员)。

NotificationCenter.default.post(name: NSNotification.Name("CustomeNotificationName"), object: "Object", userInfo: ["key":"Value"])

注意:-当你离开屏幕时,你需要删除观察者。如。

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self);
}

在swift 2.2 - XCode 7.3中,我们为NSNotificationCenter使用#选择器

 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)