[英]How to create Custom Notification Center in iOS swift
我是 ios 新手,我想在 ios 中廣播一些操作,我們有使用它的通知中心我可以在特定控制器中發布和接收但我的要求是在 Android 中我們有類似的廣播接收器我想在 ios 中創建自定義通知中心,如果我先發送一些動作,然后它會打開特定的視圖控制器。我創建了自定義通知中心,但它沒有觸發。
代碼:
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")
}
}
在您的示例中,您發布到默認通知中心。 由於該通知中心不是 MainReciever 的實例,因此不會覆蓋其功能。
要完成這項工作,您應該創建自己的 MainReciever 單例實例,並將您的帖子發送到 MainReciever 中的該實例。
可以在此處找到有關如何創建單例的信息: Singleton with Swift 3.0
(我現在它有點老了,但它可能會有所幫助。)
如果您創建自定義“默認”,您可以輕松使用您的代碼:
public extension NotificationCenter {
class var `myCenter`: NotificationCenter {
return MainReceiver.sharedInstance
}
}
修改您收到的類以添加一個共享實例:
public class MainReceiver: NotificationCenter {
public static let sharedInstance: MainReceiver = {
MainReceiver()
}()
}
然后只需調用:
NotificationCenter.myCenter.post(name: Notification.Name(rawValue: "key"), object: nil)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.