【问题标题】:How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?如何使用 swift 3.0 中的 NotificationCenter 和 swift 2.0 中的 NSNotificationCenter 传递数据?
【发布时间】:2016-08-22 23:58:49
【问题描述】:

我正在我的 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 并将其包含在被调用的函数中?

【问题讨论】:

  • 使用用户信息的方法...NSNotificationCenter.defaultCenter().postNotificationName("hideSpinner", object: nil, userInfo: yourvalue)
  • 嗯,好的,我怎样才能在该通知调用的函数中获取这个yourValue(在showSpinningWheel中)?
  • notification.userinfo一样使用.userinfo

标签: ios swift swift3 nsnotificationcenter nsnotifications


【解决方案1】:

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

Swift 3.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)

【讨论】:

    【解决方案2】:

    这在 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)
    

    【讨论】:

      【解决方案3】:

      这就是我实现它的方式。

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

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

          【讨论】:

          • 为我工作 Swift 4
          【解决方案6】:

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

          希望对您有所帮助。谢谢

          【讨论】:

          • 应该是 notification.userinfo,而不是 notification.object
          • 如果您从objective-c 类/通知接收对象/字典,您必须使用.object。如果您从 Swift 通知中接收对象,请使用 .userInfo。如果它是 .object 或 .userInfo 则跟踪您的通知: func observerNotification(notification: NSNotification){ print("Notification Received :", notification) }
          • 确保在发布到该通知键之前,如果您要跨线程发送,则在该键上设置观察者。你可能更熟悉监听器和事件这两个术语。
          猜你喜欢
          • 2017-02-22
          • 1970-01-01
          • 1970-01-01
          • 2017-06-02
          • 1970-01-01
          • 2014-07-25
          • 1970-01-01
          • 2017-06-23
          • 2015-02-23
          相关资源
          最近更新 更多