2017-04-01 58 views
2

我正在嘗試創建一個在所有應用程序生命期間保持活躍狀態​​的Firebase觀察者。我想要的是當firebase中的某些數據發生更改時,更改tabBarController的屬性。這裏是我的代碼:在所有的應用程序生活中,Firebase觀察者

self.ref.child("mySubRef").observe(.value , with: {snapshot in 

     self.tabBarController?.tabBar.items?[3].badgeValue = "!" 

    }) 

於是,我試着在我的第一個的viewController的viewDidLoad中以及在viewDidAppear創建它。我不會刪除它,因爲我希望它永遠在那裏。在viewDidAppear中,它僅在更改時處於該viewController中的情況下有效。如果我想要改變發生,無論我在哪裏(總是在tabBar內),我必須在那裏放置代碼?

感謝您的幫助!

回答

2

我已經找到了答案。問題是,當我在viewControllers之間改變時,對觀察者的引用被釋放。因此,要解決這個問題,我創建了一個類是這樣的:

class NotificationListener: NSObject { 

let ref:FIRDatabaseReference = FIRDatabase.database().reference() 
var user:User? 

func setUpListener(tabBarController:UITabBarController){ 

    self.user = User() 
    self.ref.child("users/" + self.user!.uid + "/notifications").observe(.value , with: {snapshot in 

     tabBarController.tabBar.items?[3].badgeValue = "!" 

    }) 

} 

} 

現在我有一個類的屬性,在每一個的viewController和每個人都有相同的對象的引用。當我在VC之間切換時,它不會釋放對象,因爲它仍然會被引用。

0

我想,你可以使用Appdelegate didFinishLaunchingWithOptions方法,但我不確定。

像這樣:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    // Override point for customization after application launch. 

    FIRApp.configure() 

    FIRDatabase.database().reference().child("mySubRef").observe(.value, with: { (snapshot) in 
     //I'm not sure for this part. 
     UITabBarController.init().tabBar.items?[3].badgeValue = "!" 
    }) 

    return true 
} 
+0

感謝您的回答,事情是我需要從視圖控制器(我需要用戶登錄)的一些信息,有沒有辦法從viewController做到這一點? –

+0

另一種方式Timer方法。此方法在您指定的時間重複操作。看看這個https://www.hackingwithswift.com/example-code/system/how-to-make-an-action-repeat-using-timer如果你想重複另一個控制器的動作,不要調用invalidate方法。 –

+0

或者您可以直接檢查用戶是否登錄了appdelegate。 –