andrewF
andrewF

Reputation: 54

Element not appending to array from FireBase

I finally was able to pull data from firebase, and I can display it, but for some reason it is not appending to the array I want it to here is my code:

override func viewDidLoad() {
    super.viewDidLoad()
    var arr = [String]()
    DataService.instance.recievers.observeSingleEvent(of: .value) {(recipients: FIRDataSnapshot) in
        if let recievers = recipients.value as? [String]{
            for i in recievers{
                print(i)
                arr.append(i)
            }
        }
    }

    for i in arr{
        print(i)
    }
}

The data is printing to the console from the print(i) statement, but once I leave the first for loop it empties the array. Can anyone tell me why, and how to fix this?

Upvotes: 0

Views: 190

Answers (1)

Andrew Brooke
Andrew Brooke

Reputation: 12153

The Firebase code is asynchronous. It is appending it, but by the time it appends it to the array, your

for i in arr {
    print(i)
}

statement has already executed. You should callback to a function from inside observeSingleEvent to do something after you retrieve the data from Firebase.

override func viewDidLoad() {
    super.viewDidLoad()
    var arr = [String]()
    DataService.instance.recievers.observeSingleEvent(of: .value) {(recipients: FIRDataSnapshot) in
        if let recievers = recipients.value as? [String]{
            for i in recievers{
                print(i)
                arr.append(i)
            }
            displayArray(arr)
        }
    }
}

func displayArray(name: [String]) {
    for i in arr{
        print(i)
    }
}

Upvotes: 2

Related Questions