Search code examples
swiftswift3

NotificationCenter Post request never gets received


I am trying to post a message to an observable in my app but for some reason it doesn't work at all and the only thing I can attribute it to is installing https://bugfender.com/ can anyone tell me what is wrong with this code or how to track down the root cause as there is no error messages at all

Both snippets have been moved to AppDelegate

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


     NotificationCenter.default.post(name: Notification.Name("TestPost"), object: nil)
     NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: Notification.Name("TestPost"), object: nil)

    return true
  }

and the receiver functions is

    @objc func onDidReceiveData(_ notification:Notification) {
        // Do something now
        print("XXXXXX received")
    }

===== Updating with my actual code for custom capacitor plugin =======

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    ... code for receiving notification starts here

     NotificationCenter.default.post(name: Notification.Name("TestPost"), object: nil)

    ... code for receiving notification ends here


    return true
  }
import Foundation
import Capacitor

@objc(myHelpers)
public class myHelpers: CAPPlugin {

    public override func load() {
        print("PluginLoaded")

       let nc = NotificationCenter.default
            nc.addObserver(self, selector: #selector(handleSignal), name: Notification.Name("TestPost"), object: nil)

    }

    @objc func handleSignal()
    {
    print("XX WE RECEIVED AN EVENT AT handleSignal")
        notifyListeners(
            "myPluginEvent",
            data: [:],
            retainUntilConsumed: true
        )
    }    


}

Solution

  • You need to register your observer before you post the notification.