Firebase Firestore iOS 多种型号
Posted
技术标签:
【中文标题】Firebase Firestore iOS 多种型号【英文标题】:Firebase Firestore iOS Multiple Models 【发布时间】: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
【问题讨论】:
【参考方案1】:如果您想了解数据模型的最佳实践以及如何构建数据,请查看这两个链接 [1] [2]。它还有一些视频,可以帮助您开始使用 Firestore。
[1]https://firebase.google.com/docs/firestore/data-model
[2]https://firebase.google.com/docs/firestore/manage-data/structure-data
【讨论】:
以上是关于Firebase Firestore iOS 多种型号的主要内容,如果未能解决你的问题,请参考以下文章
Firebase Firestore iOS:如何将图像保存到 Firestore 中的集合中?
在 Swift 和 ios 14 中访问 Firebase Firestore 文档的字段?
Xcode 10 iOS firebase firestore SDK -- 多个命令在 Firebase 中产生 gRPCCertificates.bundle 错误