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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36910965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:58:15  来源:igfitidea点击:

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

iosswiftswift3nsnotificationcenternsnotifications

提问by user3766930

I'm implementing socket.ioin my swift ios app.

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

Currently on several panels I'm listening to the server and wait for incoming messages. I'm doing so by calling the getChatMessagefunction in each panel:

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

However I noticed it's a wrong approach and I need to change it - now I want to start listening for incoming messages only once and when any message comes - pass this message to any panel that listens to it.

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

So I want to pass the incoming message through the NSNotificationCenter. So far I was able to pass the information that something happened, but not pass the data itself. I was doing that by:

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

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

then I had a function called:

然后我有一个函数叫做:

func showSpinningWheel(notification: NSNotification) {
}

and any time I wanted to call it I was doing:

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

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

So how can I pass the object messageInfoand include it in the function that gets called?

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

回答by Sahil

Swift 2.0

斯威夫特 2.0

Pass info using userInfowhich is a optional Dictionary of type [NSObject : AnyObject]?

使用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 version and above

Swift 3.0 及以上版本

The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift

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

NOTE:Notification “names” are no longer strings, but are of type Notification.Name, hence why we are using NSNotification.Name(rawValue:"notificationName")and we can extend Notification.Name with our own custom notifications.

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

回答by Sachin Rasane

For Swift 3

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

For Swift 4

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

回答by Ilesh P

Hello @sahil I update your answer for swift 3

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

Hope it's helpful. Thanks

希望它有帮助。谢谢

回答by Nitin

this is how I implement it .

这就是我实现它的方式。

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

回答by Mohammad Muddasir

In swift 4.2 I used following code to show and hide code using NSNotification

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