简体   繁体   English

如何初始化 Firestore 文档参考 Swift

[英]How to Initialize Firestore Document Reference Swift

I have a user model as per the below which gives me a dictionary of a User .我有一个用户 model ,如下所示,它给了我一个User的字典。

import UIKit
import FirebaseFirestore

protocol SerializeUser {
    init?(dictionary: [String: Any])
}

struct User {
    var documentRef: DocumentReference?
    var displayName: String
    var photoURL: String
    var email: String
    var isEmployee: Bool

    var dictionary: [String: Any] {
        return ["displayName": displayName, "photoURL": photoURL, "email": email, "isEmployee": isEmployee]
    }
}

extension User: SerializeUser {
    init?(dictionary: [String: Any]) {
        guard
        let displayName = dictionary["displayName"] as? String,
        let photoURL = dictionary["photoURL"] as? String,
        let isEmployee = dictionary["isEmployee"] as? Bool,
        let email = dictionary["email"] as? String else { return nil }
        self.init(displayName: displayName, photoURL: photoURL, email: email, isEmployee: isEmployee)
    }
}

I need to initialize the documentRef within my User struct somehow any ideas on how to do that?我需要以某种方式在我的User结构中初始化documentRef关于如何做到这一点的任何想法? please.请。

Somewhere you need an instance of your database to build the document reference.在某个地方,您需要一个数据库实例来构建文档参考。

var db: Firestore? = Firestore.firestore()

struct User {
    lazy var documentRef: db.collection("users").document(displayName)
}

I don't see a document id referenced anywhere here so I assumed you're using displayName as a key.我在这里看不到任何地方引用的文档 ID,所以我假设您使用 displayName 作为键。 Declaring the variable as lazy lets you initialize it with your other instance variables.将变量声明为惰性可以让您使用其他实例变量对其进行初始化。

Hope this helps.希望这可以帮助。

I have solved this by using Decodable Protocol as illustrated in this post;我已经通过使用可解码协议解决了这个问题,如本文所示; Using Decodable to get the object and document ID with Firestore 使用 Decodable 获取 object 和带有 Firestore 的文档 ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM