【发布时间】:2020-05-04 07:26:32
【问题描述】:
我是 Firestore 的新手,正在努力尝试在 iOS 上找到具有几层的项目示例。我想利用 Firestore 提供的所有功能。
我有一个将测验映射到用户的用户设置。 (一切正常)现在我想建立我的测验结构。有问题的测验对象,这些问题有答案。
我已经将它构建到了一定的水平,但感觉很老套。谁能与我分享他们的最佳实践知识?这将不胜感激。
到目前为止的工作:
Firestore 格式:“/quizzes/idone/questions/idtwo/questions”
struct Quiz: Codable, Identifiable {
@DocumentID var id: String?
var title: String
var score: Int?
var completed: Bool
@ServerTimestamp var createdTime: Timestamp?
var userId: String?
var questions: [Question]?
}
struct Question: Codable, Identifiable {
@DocumentID var id: String?
var title: String?
var completed: Bool?
//TODO: Answers
}
do {
var userQuiz = quiz
userQuiz.userId = self.userId
let questionOne = Question(title: "What day is it today?",
imageName: "test.jpeg",
completed: false)
let questioTwo = Question(title: "What is the meaning of life?",
imageName: "test.jpeg",
completed: false)
let _ = try db
.collection("quizzes").addDocument(from: userQuiz) // Works perfect
.collection("questions").addDocument(from: questionOne) // Here is the issue I can't add multiple questions.
}
catch {
fatalError("Unable to encode quiz: \(error.localizedDescription).")
}
private func loadData() {
if listenerRegistration != nil {
listenerRegistration?.remove()
}
listenerRegistration = db.collection(quizzesPath)
.whereField("userId", isEqualTo: self.userId)
.order(by: "createdTime")
.addSnapshotListener { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
self.quizzes = querySnapshot.documents.compactMap { document -> Quiz? in
try? document.data(as: Quiz.self)
}
//Todo: This is the main part I have a issue at. How do I consume my questions and mapp them to quizzes
let questions = querySnapshot.documents.compactMap { document -> [Question]? in
try? document.data(as: [Question].self)
}
//self.quizzes.questions = questions
}
}
}
【问题讨论】:
标签: ios swift firebase google-cloud-firestore