简体   繁体   中英

swift firebase iterate each snapshot value to update / set a value

Im trying to fetch all data from firebase database and update or set(if nil) each value differently. for example i have 5 users:

[1-jon likedby:jef, 2-jef likedby:nil, 3-jake, 4-mat, 5-taylor likedby:jon]

It should update/set each value differently (when button pressed update/set value and go to next value.

my code shows that i could iterate but i have no ideas on how to set each value.
or is it not possible in firebase snapshot ? if so please advice/suggest on other or similar methods to solve the problem.

Database.database().reference().child("posts").observeSingleEvent(of: .value, with: { snapshot in
        print("##########")
        var dictionary = snapshot.value as! [String:AnyObject]

        for(_,value) in dictionary{
            if let firstKey = snapshot.key as? String{

                var likedby = value["Liked By"] as? String
                let name = value["name"] as? String
                let age = value["age"] as? String
                let caption = value["caption"] as? String
                let picURL = value["photoURL"] as? String
                let gender = value["gender"] as? String
                print("TTT")
                print(name, "was liked by",likedby)

                if likedby == nil || likedby != "Othman" {
                    print("****")
                    print(name)

A Firebase DataSnapshot is read-only . It's mostly used to read back data previously fetched from Firebase.

You need to use DatabaseReference.setValue method instead to update a given node. As mentioned in the comments, the DataSnapshot.ref property provides a handy way to get back a DatabaseReference corresponding to a given snapshot.

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