【发布时间】:2021-10-12 04:36:21
【问题描述】:
对编码非常陌生,如果这里有什么特别明显的地方,我们深表歉意。
我正在开发一个应用程序,可以用来跟踪我的举重训练。我这样写数据:
public func writeNewExercise(splitName: String, day: Int, exerciseNum: Int, exerciseName: String, sets: String, repsSecs: String, isTimed: Bool, completion: @escaping (Bool) -> Void) {
let user = AuthManager.shared.user
var exerciseRef: DatabaseReference!
exerciseRef = Database.database().reference(withPath: "\(user.uid)/splits/\(splitName)/day \(day)/exercise \(exerciseNum)")
var dataDictionary: [String: Any] = [:]
dataDictionary["Exercise Name"] = exerciseName
dataDictionary["Sets"] = sets
dataDictionary["Reps or Secs"] = repsSecs
dataDictionary["Is Timed"] = isTimed
exerciseRef.setValue(dataDictionary) { error, _ in
if error == nil {
completion(true)
return
} else {
completion(false)
return
}
}
}
这给了我一个 Firebase 中的 JSON 字典,如下所示:
{
"8aIzPgurRLPPEYDpXWv54r5JjvH3" : {
"splits" : {
"Test Split" : {
"day 1" : {
"exercise 0" : {
"Exercise Name" : "Curls",
"Is Timed" : false,
"Reps or Secs" : "12",
"Sets" : "4"
}
}
}
}
},
我现在要做的是提取这些数据,以便我可以将每个练习插入到 tableView 单元格中。不想对它做任何花哨的事情——只是能够查看它,这样我就可以跟随我的分裂。我这样做更多是为了练习而不是实用。我尝试了 15 种不同的方式提取数据,但无论我做什么都行不通。我完全被难住了。这是我现在的代码:
public func downloadPost(splitName: String, day: Int, completion: @escaping (Bool) -> Void){
let user = AuthManager.shared.user
var exerciseRef: DatabaseReference!
exerciseRef = Database.database().reference()
var exerciseArray = [Exercise]()
exerciseRef.child("Users").child(user.uid).child("splits").child(splitName).child("day \(day)").observe(.value) { snapshot in
if snapshot.exists(){
for x in 0...100{
let nameValue = snapshot.childSnapshot(forPath: "exercise \(x)/Exercise Name").value
let setsValue = snapshot.childSnapshot(forPath: "exercise \(x)/Sets").value
let repsOrSecsValue = snapshot.childSnapshot(forPath: "exercise \(x)//Sets/Reps or Secs").value
let isTimedValue = snapshot.childSnapshot(forPath: "exercise \(x)/Sets/Is Timed").value
let exercise = Exercise(name: "\(nameValue!)",
sets: "\(setsValue!)",
repsOrSecs: "\(repsOrSecsValue!)",
isTimed: isTimedValue as? Bool ?? false)
print(exercise.name)
print(exercise.sets)
print(exercise.repsOrSecs)
print(exercise.isTimed)
exerciseArray.append(exercise)
completion(true)
return
}
} else {
print("no snapshot exists")
}
print(exerciseArray)
}
}
Exercise 是我创建的一个自定义类,它有一个名称、组数、代表数和一个布尔“isTimed”。此代码打印:
不存在快照,[]
尝试其他的东西,我已经得到它来打印类似的东西:
空, 0, 0, 假的
我尝试过的其他一些东西是:
- 使用斜线导航而不是在 .observe.value 中链接 .childs
- 使用 .getData 代替 .observe
- 到处乱扔 DispatchQueue.main.async
- 将executiveRef设为整个数据库,然后在分配snapshot.value时调用到特定点
- 还有很多
此时我可能已经为此投入了大约 15 个小时,但我真的无法弄清楚。任何帮助将不胜感激。如果需要,我会密切关注这篇文章并发布我可能遗漏的任何信息。
谢谢!
更新
使用下面 Medo 提供的代码,一切正常。对于其他尝试做这样的事情的人,在像 Medo 演示的那样拉数组之后,只需将 tableViewCell 中的所有标签设置为 ExportedArray[indexPath.row].theClassPropertyYouWant
【问题讨论】:
标签: ios swift firebase-realtime-database uikit