如何使用Swift 3.0中的NotificationCenter和swift 2.0中的NSNotificationCenter传递数据?

use*_*930 102 nsnotifications nsnotificationcenter ios swift swift3

我正在socket.io我的swift ios应用程序中实现.

目前在几个面板上我正在监听服务器并等待收到的消息.我这样做是通过调用getChatMessage每个面板中的函数来实现的:

func getChatMessage(){
    SocketIOManager.sharedInstance.getChatMessage { (messageInfo) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //do sth depending on which panel user is
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我注意到这是一个错误的方法,我需要更改它 - 现在我想开始只收听一次传入消息,当任何消息到来时 - 将此消息传递给任何监听它的面板.

所以我想通过NSNotificationCenter传递传入的消息.到目前为止,我能够传递发生的事情的信息,但不能传递数据本身.我是这样做的:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)
Run Code Online (Sandbox Code Playgroud)

然后我有一个叫做的函数:

func showSpinningWheel(notification: NSNotification) {
}
Run Code Online (Sandbox Code Playgroud)

任何时候我想打电话给我:

NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)
Run Code Online (Sandbox Code Playgroud)

那么如何传递对象messageInfo并将其包含在被调用的函数中?

Sah*_*hil 252

Swift 2.0

传递信息使用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   
  }
 }
Run Code Online (Sandbox Code Playgroud)

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   
  }
 }
Run Code Online (Sandbox Code Playgroud)

注意:通知"名称"不再是字符串,而是Notification.Name类型,因此我们使用的原因是NSNotification.Name(rawValue:"notificationName"),我们可以使用自己的自定义通知扩展Notification.Name.

extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}

// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)


Sac*_*ane 32

对于Swift 3

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) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }
Run Code Online (Sandbox Code Playgroud)

对于Swift 4

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
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }
Run Code Online (Sandbox Code Playgroud)


Ile*_*esh 17

您好@sahil我更新了您对swift 3的回答

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) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }
Run Code Online (Sandbox Code Playgroud)

希望它有用.谢谢

  • 应该是notification.userinfo,而不是notification.object (3认同)

小智 10

这就是 Swift 5 对我有用的东西

NotificationCenter.default.addObserver(self,
                                       selector: #selector(handleMassage),
                                       name: Notification.Name("NotificationName"),
                                       object: nil)
Run Code Online (Sandbox Code Playgroud)

处理通知的方法:

    @objc func handleMassage(notification: NSNotification) {
    if let dict = notification.object as? NSDictionary {
        if let myMessage = dict["myMessage"] as? String{
            myLabel.text = myMessage
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我是这样发布的:

let dic = ["myMessage": "testing"]
NotificationCenter.default.post(name: Notification.Name("NotificationName"), object: dic)
Run Code Online (Sandbox Code Playgroud)