简体   繁体   English

如何在 iOS swift 中创建自定义通知中心

[英]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.我是 ios 新手,我想在 ios 中广播一些操作,我们有使用它的通知中心我可以在特定控制器中发布和接收但我的要求是在 Android 中我们有类似的广播接收器我想在 ios 中创建自定义通知中心,如果我先发送一些动作,然后它会打开特定的视图控制器。我创建了自定义通知中心,但它没有触发。

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.由于该通知中心不是 MainReciever 的实例,因此不会覆盖其功能。

To make this work, you should create your own singleton instance of MainReciever and send your posts to that instance within the MainReciever.要完成这项工作,您应该创建自己的 MainReciever 单例实例,并将您的帖子发送到 MainReciever 中的该实例。

information on how to create singletons can be found here: Singleton with Swift 3.0可以在此处找到有关如何创建单例的信息: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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