简体   繁体   中英

How to Initialize Firestore Document Reference Swift

I have a user model as per the below which gives me a dictionary of a 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? 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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