Swift的NotificationCenter帮助-如何使用addObserver?

pn9klfpd  于 2023-05-05  发布在  Swift
关注(0)|答案(2)|浏览(105)

我有一个通知中心调用,看起来像这样,我试图为它创建一个观察者,它只是调用同一Swift文件中的一个函数:

NotificationCenter.default.post(
    name: Notification.Name(rawValue: "JSON"), 
    object: [ "json" : "user@domain.com" ])
NotificationCenter.default.addObserver(self, 
    selector: #selector(receiveJsNotification(_:)), 
    name: NSNotification.Name ("JSON"), object: nil)

然后在我的Swift文件中,我有:

@objc
func receiveJsNotification(_ notification: Notification) {
   print("received notification");
   // how do I retrieve user@domain.com value?
}

然而,“收到通知”永远不会被打印出来,即使“post”和“addObserver”行(我在同一个类的独立函数中使用)被明确执行(print语句显示)。
我的Swift构建没有错误。使用Xcode 14.2
我做错了什么?另外,如何检索“user@domain.com”值?

agyaoht7

agyaoht71#

我不知道为什么你的代码不工作。我刚刚使用默认的iPhone应用程序模板(使用Storyboards)创建了一个示例项目
下面是ViewController类的代码:

import UIKit

class ViewController: UIViewController {
    
    let testNotification = NSNotification.Name(rawValue: "testNotification")

    @IBAction func sendNotification(_ sender: Any) {
        print("In \(#function)")
        NotificationCenter.default.post(name: testNotification, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(notifificationReceived), name: testNotification, object: nil)
    }
    
    @objc func notifificationReceived(_ theNotificaiton: Notification) {
        print("Notification received")
    }
}

当我将该代码的IBAction连接到一个按钮,运行应用程序并点击按钮时,我看到控制台上出现一条“Notification received”消息,告诉我它可以工作
显然,这是一个难以置信的幼稚的例子,它向监听它的同一个对象(视图控制器)发送通知,但它证明了通知中心的工作。

qhhrdooz

qhhrdooz2#

为了让你的代码工作,在userinfo中传递数据,而不是像下面一行那样的对象,还要确保你的addObserver代码在发布通知之前运行。

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "JSON"), object: nil, userInfo: ["json" : "your email/data"])

receiveJSNotification()中添加以下代码

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

在函数中接收到的通知对象具有userInfo字典,该字典保存调用观察者时传递的数据。可以从dictionary中获取数据并使用if let/guard let展开

相关问题