1
votes

This is my second version me trying to retrieve code from Firebase and do stuff with it. This is how I done it the second way:

    channelRef?.observe(.childChanged, with: { (snapshot) -> Void in
        let update = snapshot.value as! Dictionary<String, AnyObject>
        var readyToGoValue: Bool?
        var userID: String?
        var amountOfPlayers: Int?
        var changedCreator: String?
        if let updatedReadyToGo = update["readyToGo"] as! Bool!{
            if updatedReadyToGo == true
            {
                readyToGoValue = true
            }
            else
            {
                readyToGoValue = false
            }
        }
        if let updateduserID = update["userID"] as! String!{
            userID = updateduserID
        }
        if let updatedAmountOfPlayers = update["currentPlayers"] as! Int!{
            amountOfPlayers = updatedAmountOfPlayers
        }
        if let updateduserID = update["userID"] as! String!{
            userID = updateduserID
        }
        if let updatedCreator = update["creator"] as! String!{
            changedCreator = updatedCreator
        }

        let currentUser = FIRAuth.auth()?.currentUser?.uid

        if changedCreator != nil
        {
            print("changed creator")
            self.creator = changedCreator!
        }

This crashed with an error code:

Could not cast value of type '__NSCFString' (0x10a77f4a0) to 'NSDictionary' (0x10a780288). at the line " update". This was my first attempt:

    channelRef?.observe(.childChanged, with: { (snapshot) -> Void in
        let value = snapshot.value as? NSDictionary
        let readyToGoValue = value?["readyToGo"] as? Bool ?? false
        let userID = value?["userID"] as? String ?? ""
        var amountOfPlayers = value?["currentPlayers"] as? Int ?? 0
        let changedCreator = value?["creator"] as? String ?? ""
        print(snapshot)
        let currentUser = FIRAuth.auth()?.currentUser?.uid
        print(changedCreator)
        print(amountOfPlayers)
        if changedCreator != ""
        {
            print("changed creator")
            self.creator = changedCreator
        }

This doesn't work swell. When changing the creator (just a string) in Firebase, I get this as a print when adding print(snapshot):

Snap (creator) hi

However the print("changed creator") never is executed. Why is this?

edit: This is how I got channelRef?:

super.prepare(for: segue, sender: sender)
if let channel = sender as? Channel {
    let chatVc = segue.destination as! channelMultiplayerViewController
    chatVc.channel = channel
    chatVc.channelRef = channelRef.child(channel.id)
    chatVc.usersKey = userKey

}

Printing more data:

        print("path channel ref: " + "\(self.channelRef)")
        print("snapshot: " + "\(snapshot)")
        print("value: " + "\(value)")

-path channel ref: Optional(https://X.com/channels/-KeGKaJavH6uPYaSa7k4)

-snapshot: Snap (creator) new Creator

-value: nil

Update:

data structure:

structure

This will work for now, but isn't there a better approach?:

        if snapshot.key == "creator"
        {
            changedCreator = snapshot.value as! String
        }

Another problem, exactly the same as above but with the solution for the first problem, this problem won't get solved. When I try to get the first child node, so the first user, and trying to get their userID, nothing works. I use this code:

let firstChild = UInt(1)
                    self.channelRef?.queryLimited(toFirst: firstChild).observeSingleEvent(of: .value, with: { (snapshot) in
                        let value = snapshot.value as? NSDictionary
                        print(snapshot)
                        print(value)
                        let newCreator = value?.value(forKey: "userID") as? String

                        if newCreator != nil{
                            print("Got the userID")
                        }
                        if snapshot.key == "userID"
                        {
                            print("Got the userID")
                        }
                    })
Snap (-KeJWMiXaL-FGp0J7b3u) {
    "-KeJWO0V9kxgGnrACAtP" =     {
        PictureVersion = 2;
        readyToGo = 0;
        userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
        username = pietje;
    };
}
Optional({
    "-KeJWO0V9kxgGnrACAtP" =     {
        PictureVersion = 2;
        readyToGo = 0;
        userID = SZlQ76RLCJQpFa0CDhrgFJoYzrs2;
        username = pietje;
    };
})

And this prints out, so no userID is given. Why is this? The userID is right there! I read the docs but it should work...

1
Can you include the line where you set the channelRef? variable?Pat Needham
It's possible you gave it a path that goes one level too deep into your database structure, like "some_collection/an_object/readyToGo" instead of "some_collection/an_object", which would explain why snapshot is being returned as a string instead of a dictionaryPat Needham
I edited the question. Something is wrong when changing the data to the dictionary I thinkPetravd1994

1 Answers

0
votes

Try replacing chatVc.channelRef = channelRef.child(channel.id) with chatVc.channelRef = channelRef