我在Firebase中有一个由1和0组成的数组(基本上是真和假),它们都存储为单独的键/值对。我想从Firebase中检索它们,并将每个值附加到Swift中的数组中。
我试过这个(在SO的其他地方找到了),但它没有用。
let ref = Firebase(url:"https://<<unique>>.firebaseio.com/users/\(self.UUID)/scoreArray")
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
print("snap is null")
} else {
let enumerator = snapshot.children
while let rest = enumerator.nextObject() as? FDataSnapshot {
self.scoreArray.append(rest.value! as! String)
}
}
})
它没有崩溃,它只是没有填充数组,即使我print(rest.value)
它会给我数组。
所以我想问题是,如何将rest.value
转换为可用的表单?
根据要求编辑Firebase结构。
66EC8AC4-<<rest of UUID>>
creation_date: "Jun 10, 2016"
extra_quiz_1
q1: "a"
q10: "b"
<<Continues>>
scoreArray
0: "0"
1: "1"
2: "0"
3: "0"
<<continues>>
答案 0 :(得分:0)
在Firebase中使用Array是一项挑战,通常有更好的结构数据选择。
在这个用例中,它可能会起作用,所以这就是它的完成方式。
给出类似于你的结构:
quiz_0
quiz_name: The Planets
scores
0: Mercury
1: Venus
2: Earth
这是你如何阅读数据
let quizzesRef = self.myRootRef.childByAppendingPath("quizzes")
quizzesRef.observeEventType(.Value, withBlock: { snapshot in
for child in snapshot.children {
let quiz_name = child.value["quiz_name"] as! String
print(quiz_name)
let scores = child.value["scores"] as! NSArray
print(scores) //scores is an array
let answer0 = scores[0] //just to demonstrate accessing the array
print(answer0)
}
})
和输出
Planets
(
Mercury,
Venus,
Earth
)
Mercury
话虽如此,不要使用数组。这是一个可能更灵活的建议。重新编号问题非常简单,修改问题或答案也很容易。 -Asidijaid键是使用childByAutoId生成的 - 有助于将动态数据与静态键分离。
quiz_0
quiz_name: The planets
quiz_data
-Asok99idkasdsl
question_number: 0
question: Which planet closet to the Sun?
answer: Mercury
-Yklaosokjdinoisd
question_number: 1
question: Which rocky planet is hotter than Mercury
answer: Venus
-Klkooksow999sdd
question_number: 2
question: What is the third planet from the Sun
answer: Earth