简体   繁体   中英

Firebase & Swift: Performing segue after fetching data

When people log in to my app, I take some data from the database like this:

func DownloadButikker() {
    self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let store = Store()
            store.Latitude = dictionary["Latitude"]?.doubleValue
            store.Longitude = dictionary["Longitude"]?.doubleValue
            store.Store = dictionary["Store"] as? String
            store.Status = dictionary["Status"] as? String
            stores.append(store)
        }
    })
    self.performSegue(withIdentifier: "LogInToMain", sender: nil)
}

I perform the segue before all data has finished loading. Are there any way to get a completion to the observer or check if all data is loaded before making the segue?

The quick solution is that you need to perform your segue after finishing your async call.

func DownloadButikker() {
    self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let store = Store()
            store.Latitude = dictionary["Latitude"]?.doubleValue
            store.Longitude = dictionary["Longitude"]?.doubleValue
            store.Store = dictionary["Store"] as? String
            store.Status = dictionary["Status"] as? String
            stores.append(store)
        }
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: "LogInToMain", sender: nil)
        }
    })
}
func DownloadButikker(completion: Bool = false) {
    self.ref?.child("Stores").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let store = Store()
            store.Latitude = dictionary["Latitude"]?.doubleValue
            store.Longitude = dictionary["Longitude"]?.doubleValue
            store.Store = dictionary["Store"] as? String
            store.Status = dictionary["Status"] as? String
            stores.append(store)
            completion(true)
        }
    })
}


// In your ViewController
func myFunction() {
   DownloadButikker { (hasFinished) in
      if hasFinished { 
         self.performSegue(withIdentifier: "LogInToMain", sender: 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