View Controller loads before data is pulled from firebase login - Swift

扶醉桌前 提交于 2019-12-04 21:07:19

This is a common issue:

Firebase is asynchronous and viewWillAppear is occurring before Firebase has had time to return the data. This code

 playNumberRef.observeSingleEventOfType

is a block and the app should not proceed to show the next view until that block has the returned data.

In other words, show the next view from inside that block

I don't know how the rest of your code is set up, but here's a quickie example (untested so don't copy paste)

Suppose we have a loginViewController that lets the user login, and then a mainViewController for the main app view after the user logs in.

In the AppDelegate we have

func showMainView() {

    let storyboard = NSStoryboard(name: "Main", bundle: nil)

    self.mainVC = (storyboard.instantiateControllerWithIdentifier("MainViewController") as? NSViewController)!

    self.mainVC.showWindow(self)

}

so in your case the block could be modified thusly:

playNumberRef.observeSingleEventOfType(.Value, withBlock: { snap in

   if let checkPlay = snap.value as? NSNumber {

     userSettings.setInteger(Int(checkPlay), forKey: "playNumber")

     let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate

     appDelegate.showMainView() //prepare to sho the main view

     self.view.window?.close() //get rid of this one

}})

So the main view controller is only displayed when Firebase has had a time to return the data and the vars are populated.

 if let checkPlay = snap.value as? NSNumber {
     dispatch_async(dispatch_get_main_queue(),{
        userSettings.setInteger(Int(checkPlay), forKey: "playNumber")
     })
 }})

Try this, it can help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!