问题
This is my first attempt at XCode, used to work on MatLab so very new to this. I have a VC here (named guests2ViewController) which I'm trying to send data to the next VC (named resultsViewController). Unfortunately the VC is exporting the data from the lines (print "b") instead of the earlier lines (print "a"). Why is this, and how could I fix it?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as? resultsViewController
if segue.identifier == "toresults"{
//prioritise this part of code - call it part A
Database.database().reference(withPath: self.password).observeSingleEvent(of: .value, with: { snapshot in
//dates
var arr = [String]()
//times
var arr1 = [String]()
//number of attendees
var arr2 = [String]()
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? DataSnapshot {
let newobj=rest.children
while let rest1 = newobj.nextObject() as? DataSnapshot {
arr.append(rest.key)
arr1.append(rest1.key)
arr2.append(String(rest1.childrenCount))
let guests = arr2.max()
var index = 0
for n in arr2 {
if n == guests {
//print (index)
let datefromarray = String(arr[index])
let timefromarray = String(arr1[index])
let guests1 = String(Int(guests!)!)
vc?.databasedate = (datefromarray)
vc?.databasetime = (timefromarray)
vc?.databaseguests = (guests1)
break
}
index += 1
}
}
}
print(vc?.databasedate)
print(vc?.databasetime)
print(vc?.databaseguests)
print("a")
//this doesn't get sent to the next VC after taking the data from Firebase
})
}
print(vc?.databasedate)
print(vc?.databasetime)
print(vc?.databaseguests)
print("b")
//this gets sent to the next VC
}
}
回答1:
Data is loaded from Firebase (and most modern web APIs) asynchronously. This is to prevent blocking the user from using your app, while the (possibly slow) network request is in progress.
If you check in a debugger, you'll see that print("b")
happens before vc?.databasedate = (datefromarray)
, which explains why you're passing the wrong value to the next view controller.
The solution is always the same: any code that needs data from the database needs to be inside the callback/closure/completion handler, or be called from there.
For more on this and code examples, see:
- Firebase with Swift 3 counting the number of children
- Why isn't my function that pulls information from the database working?
- Access Firebase variable outside Closure
- getting data out of a closure that retrieves data from firebase
- Swift / How to use dispatch_group with multiple called web service?
- Completion handler Firebase observer in Swift
来源:https://stackoverflow.com/questions/65447695/how-do-you-force-the-viewcontroller-to-export-the-data-in-b-instead-of-a-to