NotificationCenter在Swift中传递数据

问题描述 投票:9回答:4

我正在研究Swift 3中的测试项目。我正在尝试使用NotificationCenter将textField字符串从一个类传递到另一个类。我试图通过这个链接来解决答案:pass NSString variable to other class with NSNotificationhow to pass multiple values with a notification in swift

我从上面的链接尝试了几个答案,但没有任何效果。

我的代码:

//第一个VC

import UIKit


extension Notification.Name {        
public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey")    
}


class ViewController: UIViewController {

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func sendData(_ sender: AnyObject) {

    let userInfo = [ "text" : textView.text ]
    NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo)

}

}

// SecondVC

 import Foundation
 import  UIKit

 class viewTwo: UIViewController {

@IBOutlet weak var result: UILabel!



override func viewDidLoad() {


}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: .myNotificationKey, object: nil)
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: .myNotificationKey, object: nil)
}

func notificationReceived(_ notification: Notification) {
    guard let text = notification.userInfo?["text"] as? String else { return }
    print ("text: \(text)")

    result.text = text
}

enter image description here}

我不确定代码有什么问题。上面,代码最初标记为答案,我从第一个链接中找到。代码已转换为Swift。

ios swift uiviewcontroller nsnotificationcenter
4个回答
20
投票

不要使用object参数传递数据。它旨在过滤具有相同名称但来自特定对象的通知。因此,如果在addObserver发布通知和另一个对象时传递了一些对象,则不会收到它。如果你传递nil,你基本上会关闭这个过滤器。

你应该使用userInfo参数。

首先,最好将通知的名称定义为Notification.Name的扩展名。这种方法更安全,更易读:

extension Notification.Name {        
    public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey")    
}

发布通知:

let userInfo = [ "text" : text ]
NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo)

订阅:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: .myNotificationKey, object: nil)
}

退订:

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: .myNotificationKey, object: nil)
}

要调用的方法:

func notificationReceived(_ notification: Notification) {
    guard let text = notification.userInfo?["text"] as? String else { return }
    print ("text: \(text)")
}

4
投票

使用userInfo传递文本,@IBAction func sendData(_ sender: UIButton) { // post a notification NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: ["text": textValue.text]) print(textValue) // textValue printing } 是类型[AnyHashable:Any]的可选字典?在Swift 3.0中它是[NSObject:AnyObject]?在swift 2.0中

viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(self. incomingNotification(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

//注册接收通知

func incomingNotification(_ notification: Notification) {
if let text = notification.userInfo?["text"] as? String {
   print(text)
  // do something with your text   
}


}

并在收到通知

sendData

1
投票

在你的textField.text方法中,将incomingNotification传递给Notification对象并在你的guard let theString = notification.object as? String else { print("something went wrong") return } resultLabel.text = theString 中执行以下操作:

dispatchQueue

您还可以使用块在控制器之间传递数据。


1
投票

使用@IBAction func sendData(_ sender: AnyObject) { let userInfo = [ "text" : textView.text ] DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo) } } 是因为您的通知是在视图加载之前发布的。因此,只需延迟通知发布。

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.