1

I am new to ios,I wanted to broadcast some action in ios we have notification center using this I can post and receive in specific controller but my requirement is in Android we have broadcast receiver similarly I want to create custom notification center in ios if I send some action first it receives then it open specific view controller.I created custom notification center but it is not triggering.

code:

NotificationCenter.default.post(name: Notification.Name(rawValue: "key"), object: nil)
class MainReceiver: NotificationCenter
{
    override func post(name aName: NSNotification.Name, object anObject: Any?)
    {
        print("coming here")
    }

}
dark knight
  • 303
  • 1
  • 4
  • 15

2 Answers2

0

In your example, you posted to the default notification center. Since that notification center is not an instance of MainReciever, it's function will not be overridden.

To make this work, you should create your own singleton instance of MainReciever and send your posts to that instance within the MainReciever.

information on how to create singletons can be found here: Singleton with Swift 3.0

0

(I now it's a bit old, but it might help.)

if you create a custom "default", you could easily use your code:

public extension NotificationCenter {
   class var `myCenter`: NotificationCenter {
      return MainReceiver.sharedInstance
   }
}

modify you received class to add a sharedInstance:

public class MainReceiver: NotificationCenter {
   public static let sharedInstance: MainReceiver = {
       MainReceiver()
   }()
}

and then just call :

NotificationCenter.myCenter.post(name: Notification.Name(rawValue: "key"), object: nil)
kew
  • 121
  • 1
  • 6