【问题标题】:Why am I able to upload custom object as a field to a firestore document?为什么我可以将自定义对象作为字段上传到 Firestore 文档?
【发布时间】:2020-12-03 03:17:31
【问题描述】:

Firestore 数据类型混淆:

我正在尝试上传用户文档,但不包括琐碎的字段,作为另一个 Firestore 文档的字段。有点像“迷你用户文档”,只包含他们的 uid、用户名、姓名和个人资料图片。

为什么“添加数据”的 Firestore 文档声明支持自定义对象,但在“支持的数据类型”中没有列出对象?

手头的问题:

它说自定义对象被翻译成支持的数据类型,但是当我按照文档上传对象时出现错误:

Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Unsupported type: __SwiftValue (found in field tempUserA)'

public class ConsolidationDataService {
    
    static let instance = ConsolidationDataService()
    let db = Firestore.firestore()
    
    func createNewBucket(bucket: Bucket, user: UserDictionary, collections: [String], handler: @escaping(_ completed: Bool)-> ()){
        let tempUserA = TempUser(
            uid: user.uid,
            username: user.username,
            profileImageURL: user.profileImageURL,
            fullname: user.fullname
        )
        let tempUserB = TempUser(
             uid: "",
             username: "",
             profileImageURL: "",
             fullname: ""
        )
        
        let bucketRef = db.collection("ConsolidatedBuckets").document()
        let consolidatedId = bucketRef.documentID
        let consolidatedBucket = [
            "consolidatedBucketId": consolidatedId,
            "bucketTitle": bucket.bucketTitle,
            "creatorUsername": user.username,
            "creatorUid": user.uid,
            "bucketLogCount": 1,
            "completedCount": 0,
            "uncompletedCount": 1,
            "bucketIds": [bucket.bucketId],
            "bucketImages": [],
            "collectionIds": [],
            "tempUserA": tempUserA,
            "tempUserB": tempUserB
        ] as [String : Any]
        bucketRef.setData(consolidatedBucket){ (error) in
            if error != nil {
                print("There was an error creating a new document in the ConsolidatedCollection")
                handler(false)
            } else {
                print("Uploaded new bucket in the consolidated bucekts colleciton. Named: \(bucket.bucketTitle)")
                handler(true)
        }
    }
}

public struct TempUser: Codable {
    let uid: String?
    let username: String?
    let profileImageURL: String?
    let fullname: String?
    
    enum CodingKeys: String, CodingKey {
        case uid
        case username
        case profileImageURL
        case fullname
    }
}

我还尝试使用TempUser 自定义结构的结构定义中的字典上传对象。它也不允许将对象转换为 Firestore 接受的数据类型。

public struct TempUser: Codable {
    let uid: String?
    let username: String?
    let profileImageURL: String?
    let fullname: String?
    
    var dictionary: [String: Any] {
        let data = (try? JSONEncoder().encode(self)) ?? Data()
        return (try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any]) ?? [:]
    }
    
    enum CodingKeys: String, CodingKey {
        case uid
        case username
        case profileImageURL
        case fullname
    }
}

函数调用者

ConsolidationDataService.instance.createNewBucket(bucket: uploadedBucket, user: self.user!, 
    collections: self.collectionsBeingAddedToArray) { (completed) in
        if completed {
            print("Finished.")
            self.showAlert()
        }
}

其中collectionsBeingAddedToArray[String] 类型,userUserDictionary 类型,这是用户对象的自定义结构。

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    没有足够的信息来评估第二个示例。在第一种情况下,TempUser 结构实例必须转换为 [String: Any] 字典。

    
        let encodedTempUserA: [String: Any]
        let encodedTempUserB: [String: Any]
        do {
            encodedTempUserA = try Firestore.Encoder().encode(tempUserA)
            encodedTempUserB = try Firestore.Encoder().encode(tempUserB)
        } catch {
            handleEncodingError(error)
            return
        }
    
        let consolidatedBucket = [
                "consolidatedBucketId": consolidatedId,
                "bucketTitle": bucket.bucketTitle,
                "creatorUsername": user.username,
                "creatorUid": user.uid,
                "bucketLogCount": 1,
                "completedCount": 0,
                "uncompletedCount": 1,
                "bucketIds": [bucket.bucketId],
                "bucketImages": [],
                "collectionIds": [],
                "tempUserA": encodedTempUserA,
                "tempUserB": encodedTempUserB
            ] as [String : Any]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 2018-06-11
      相关资源
      最近更新 更多