ios - Firebase Firestore iOS 多种型号
问题描述
我是 Firestore 的新手,正在努力尝试在 iOS 上找到具有几层的项目示例。我想利用 Firestore 提供的所有功能。
我有一个将测验映射到用户的用户设置。(一切正常)现在我想建立我的测验结构。有问题的测验对象,这些问题有答案。
我已经将它构建到一定水平,但感觉很hacky。谁能与我分享他们的最佳实践知识?这将不胜感激。
工作至今:
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
}
}
}
解决方案
如果您想了解数据模型的最佳实践以及如何构建数据,请查看这两个链接 [1] [2]。它还有一些视频,可以帮助您开始使用 Firestore。
[1] https://firebase.google.com/docs/firestore/data-model
[2] https://firebase.google.com/docs/firestore/manage-data/structure-data
推荐阅读
- php - 从多维数组php中完全删除重复项
- reactjs - 如何更改材质 ui 粘性标题表中的颜色?
- unit-testing - 在 ForEach 方法中使用短动作调用语法时不调用 Moq
- amazon-web-services - 使用 bitbucket 作为源时,Terraform 无法从模块中获取参数
- c - C中实用的延续传递风格?
- c++ - 如何将 Json 文件仅解析为 cpp 中的原始字符串值。我正在使用 nlohmann json 库进行解析
- java - 从 Firestore 中删除没有集合名称的文档
- julia - 绘制具有多个标记形状的线
- amazon-web-services - 监控 ssl aws ALB 时 Zabbiks 项的错误
- php - PHPUnit 代码覆盖率“没有可用的代码覆盖率驱动程序”,PECL 失败