articga
articga

Reputation: 385

Read array from firebase once and put it into an array

How to read firebase array and put it into swift array? I'm trying to solve this problem for like 4 hours. What am I doing wrong?

enter image description here

ref.child("names").child("myNames").observe(.value) { (snapshot) in
        if let item = snapshot.value as? String {
            namesArray.append(item)
        }
    }

Upvotes: 0

Views: 77

Answers (2)

EDUsta
EDUsta

Reputation: 1933

You should parse the snapshot as [String : Any]? and fetch the values in the dictionary.

ref.child("names").child("myNames").observe(.value) { (snapshot) in
    if let itemDictionary = snapshot.value as? [String : Any] {
        for (key, value) in itemDictionary {

            // Another check for String
            if let valueString = value as? String {
                namesArray.append(valueString)
            } 
        }
    }
}

Upvotes: 2

creeperspeak
creeperspeak

Reputation: 5523

You are trying to unwrap an array of String as a single String, so that is why it's failing. Change to the following:

ref.child("names").child("myNames").observe(.value) { (snapshot) in
    if let item = snapshot.value as? [String] {
        namesArray = item
    }
}

Upvotes: 0

Related Questions