在Swift中将值从struct更新到Firestore

时间:2018-10-25 16:56:40

标签: ios swift firebase google-cloud-firestore

我想从struct更新值,这是我的struct代码。

struct Usersdata {
let uid:String?
let facebook:String?
let google : String?
let name : String?
let age : Int?
let birthday : String?
let smokeage  : Int?
let smokeaddiction : Int?
let smokebrand  : String?
let gold : Int?
let score : Int?
let fish : Int?
let shit : Int?
let userimage  : String?
init(aDoc: DocumentSnapshot) {
    self.uid = aDoc.get("uid") as? String ?? ""
    self.facebook = aDoc.get("facebook") as? String ?? ""
    self.google = aDoc.get("google") as? String ?? ""
    self.name = aDoc.get("name") as? String ?? ""
    self.age = aDoc.get("age") as? Int ?? 0
    self.birthday = aDoc.get("birthday") as? String ?? ""
    self.smokeage = aDoc.get("smokeage") as? Int ?? 0
    self.smokeaddiction = aDoc.get("smokeaddiction") as? Int ?? 0
    self.smokebrand = aDoc.get("smokebrand") as? String ?? ""
    self.gold = aDoc.get("gold") as? Int ?? 0
    self.score = aDoc.get("score") as? Int ?? 0
    self.fish = aDoc.get("fish") as? Int ?? 0
    self.shit = aDoc.get("shit") as? Int ?? 0
    self.userimage = aDoc.get("userimage") as? String ?? ""
    }
}

我从查询函数中获得了这样的值

func queryAUser() {
    let docRef = self.db.collection("Users").document(userID).collection("userdata").document("userdata")
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let aUser = Usersdata(aDoc: document)
            self.local_userdata = aUser
        } else {
            print("Document does not exist")
        }
    }
}

我可以使用local_userdata获取我的值,但是我现在想将新值更新为Firestore。

是否有解决方案来更新Usersdata.struct中的值?

1 个答案:

答案 0 :(得分:0)

让我试一下。

假设您已经使用问题中的代码读取了用户,并且该用户存储在self.local_userdata中

这是一个示例函数,用于在给定用户uid和新名称的情况下更新用户名

func updateUserName(withUid: String, toNewName: String) {
    self.db.collection("users").document(withUid).setData( ["name": toNewName], merge: true)
}

要使用此功能,请阅读self.local_userdata.uid,以便我们知道要修改的用户并传入该uid,以及新名称应为什么。

您可以进一步增强此功能,从而为此特定用户更新任何字段

func updateUserField(withUid: String, andField: String, toNewValue: String) {
    self.db.collection("users").document(withUid).setData( [andField: toNewValue], merge: true)
}

当然,如果要更改字段,还应该相应地更新结构

self.local_userdata.name =“某些名称”