我試圖從for循環中的firebase中獲取一些數據,但它不起作用。與Firebase同步的Swift DispatchQueue
我知道我應該使用DispatchQueue,但我無法理解我應該如何使用它與Firebase。
我有一個循環:
for i in 0..<Exercice.workout.count{
exercice = (Exercice.workout[i] as! [[Any]])[0][0] as! String
print("Exercice: \(exercice)")
self.endDeleteLastSerie(key: key, exercice: exercice, callback: {(status, endTime) in
if status == "success"{
print("do stuff here")
let index = self.getIndexOfExercice(exerciceName: exercice)
print("Index: \(index)")
print("ExerciceName: \(exercice)")
}
}
在我的功能endDeleteLastSerie我打電話2個火力功能
func endDeleteLastSerie(key:String, exercice: String, callback: @escaping(_ status:String, _ endTime: Int)->Void){
FirebaseWorkout.deleteSerie(key: key, exercice: exercice) { (status) in
if status == "success" {
//we set the end time to firebase
FirebaseWorkout.updateEndExercice(exercice: exercice, callback: { (status, endTime) in
if status == "success" {
callback("success", endTime)
}else{
callback("error", endTime)
}
})
}
}
}
****我火力功能的一個實例****
static func deleteSerie(key: String, exercice: String, callback: @escaping (_ status: String)->Void){
let uid = FirebaseUsers.User.uid
print("remove")
Database.database().reference().child("users/"+uid+"/workout/"+self.workoutKey+"/exercice/"+exercice+"/series/"+key).removeValue { (error, DatabaseReference) in
if error == nil {
print("removed from firebase")
callback("success")
}else{
callback("error")
}
}
}
但我「m到處是:
Exercice: Bench Press
remove
Exercice: Pectoral Fly
remove
removed from firebase
removed from firebase
do stuff here
Index: 1
ExerciceName: Pectoral Fly
do stuff here
Index: 1
ExerciceName: Pectoral Fly
我試圖加我爲循環內:
DispatchQueue.main.sync { }
或
DispatchQueue.global().sync(execute: { })
或
var _dispatchQueue:DispatchQueue = DispatchQueue(label: "first", qos: .userInteractive)
那裏面加我的for循環
self._dispatchQueue.sync { }
但是,沒有什麼工作
我怎樣才能解決這個問題?並獲得
Exercice: Bench Press
remove
removed from firebase
do stuff here
Index: 0
ExerciceName: Bench Press
Exercice: Pectoral Fly
remove
removed from firebase
do stuff here
Index: 1
ExerciceName: Pectoral Fly
你想通過在這裏使用DispatchQueue來完成什麼? Firebase SDK已經完成了主線程中的所有網絡交互。它在主線程上執行的所有操作都會調用您的回調/完成處理程序。 –
問題是,從Firebase獲得回調後,我從for循環中獲得了值。當我得到firebase的回調,我做.. let index = self.getIndexOfExercice(exerciceName:exercice),但我總是得到「胸鰭飛行」作爲exerciceName – Pierre
我在回調中添加了2更多的打印,讓你更好地理解,我是什麼好了。我添加了它們在控制檯日誌中顯示的打印。 @Frank van Puffelen – Pierre