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


121

我正在socket.io快速的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
        })
    }
}

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

所以我想通过NSNotificationCenter传递传入的消息。到目前为止,我能够传递发生了某些事情的信息,但无法传递数据本身。我这样做的原因是:

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

然后我有一个函数叫做:

func showSpinningWheel(notification: NSNotification) {
}

每当我想称呼它时,我都在做:

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

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


2
userinfo使用方法...NSNotificationCenter.defaultCenter().postNotificationName("hideSpinner", object: nil, userInfo: yourvalue)
EI队长v2.0

嗯,我如何yourValue在该通知中调用的函数中获取此信息showSpinningWheel
user3766930 '16

使用.userinfo类似 notification.userinfo
EI机长v2.0

Answers:


276

雨燕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及更高版本

现在,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)

46

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

1
为我工作Swift 4
Ravi

19

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

希望对您有所帮助。谢谢


3
应该是notification.userinfo,而不是notification.object
Ho Cheung)

1
如果要从Objective-C类/通知接收对象/词典,则必须使用.object。如果您正在从Swift通知接收对象,请使用.userInfo。使用以下功能跟踪您的通知:.object还是.userInfo,其功能为:funcobserverNotification(notification:NSNotification){print(“ Notification Received:”,notification)}
Doci

在发布到该通知密钥之前,请确保是否跨线程发送,已在该密钥上设置了观察者。您可能对术语“侦听器”和“事件”更为熟悉。
亚伦

2

这就是我的实现方式。

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

0

在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)
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.