首页 > 解决方案 > 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
        }
      }
  }

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


如果您想了解数据模型的最佳实践以及如何构建数据,请查看这两个链接 [1] [2]。它还有一些视频,可以帮助您开始使用 Firestore。

[1] https://firebase.google.com/docs/firestore/data-model

[2] https://firebase.google.com/docs/firestore/manage-data/structure-data


推荐阅读