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

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

我正在 swift ios 应用中实施 socket.io

目前我正在几个面板上监听服务器并等待传入​​的消息。我通过在每个面板中调用 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
        })
    }
}

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

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

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.showSpinningWheel(_:)), name: showSpinner, object: nil)

然后我有一个函数叫做:

func showSpinningWheel(notification: NSNotification) {
}

任何时候我想调用它我都在做:

NSNotificationCenter.defaultCenter().postNotificationName(hideSpinner, object: self)

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

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

Swift3.0、4.0、5.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
 // For swift 4.0 and above put @objc attribute in front of function Definition  
 func showSpinningWheel(_ notification: NSNotification) {

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

注意: 通知“名称”不再是字符串,而是类型 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)

你好@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
            }
        }
 }

希望对您有所帮助。谢谢

对于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
            }
        }
 }

对于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
            }
        }
 }

这就是我实现它的方式。

let dictionary = self.convertStringToDictionary(responceString)            
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)

在 swift 4.2 中,我使用以下代码使用 NSNotification

显示和隐藏代码
 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height
        print(keyboardheight)
    }
}

这就是我在 Swift 5

中工作的方法
NotificationCenter.default.addObserver(self,
                                       selector: #selector(handleMassage),
                                       name: Notification.Name("NotificationName"),
                                       object: nil)

处理通知的方法:

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

我是这样发帖的:

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

Swift 5.5 避免 #selector():

首先声明姓名:

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

接下来是添加观察者(注意队列):

// For example transferred data should implement protocol
protocol PrettyDelegate {
    func doSomethingAwesome()
}

// Here is the way how we can subscribe as observer
NotificationCenter.default.addObserver(forName: .prettyName, object: nil, queue: nil) { [weak self] notif in
    guard let self = self else { return } // Because self used more than once
    if let userInfo = notif.userInfo,
       let delegate = userInfo["pretty"] as? PrettyDelegate {
        self.delegate = delegate
    }
    
    self.makePretty() // Here we can do anything
}

最后,我们可以post来自另一个对象的通知

// Here I'll illustrate how to pass optional value as userInfo
var userInfo: [AnyHashable : Any]?
if let prettyDelegate = self as? PrettyDelegate {
    userInfo = ["pretty": prettyDelegate]
}
NotificationCenter.default.post(name: .prettyName, object: nil, userInfo: userInfo)
    

注意:不要忘记删除观察者,当你不再需要它时。