简体   繁体   中英

How to create Custom Notification Center in iOS swift

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

}

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

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM