kj15
kj15

Reputation: 11

Firebase reference object doesn't save to variable in SwiftUI

I'm storing data in Firebase and I've found a way to create an array of just the keys. The first print statement correctly prints out the array. However, outside of the database reference, the variable listOfBannedNames doesn't seem to save the array. The array prints out as [] with none of the keys inside. I would like to store the array in the variable listOfBannedNames to be used later.

    let username = username
    let formattedUsername = formatUsername(username: username)
    var listOfBannedNames = [String]()
    ref.observeSingleEvent(of: .value, with: {
        snapshot in
        var bannedNamesList = [String]()
        for bannedNames in snapshot.children {
            bannedNamesList.append((bannedNames as AnyObject).key)
        }
        listOfBannedNames = bannedNamesList
        print(listOfBannedNames)
    })
    print(listOfBannedNames)

Upvotes: 1

Views: 202

Answers (1)

Eduard
Eduard

Reputation: 310

Thats exactly about async behavior. Try to make the following:

func makeRequestToFirebase(completion: @escaping ([String]) -> Void) {
    ref.observeSingleEvent(of: .value, with: {
        snapshot in
        var bannedNamesList = [String]()
        for bannedNames in snapshot.children {
            bannedNamesList.append((bannedNames as AnyObject).key)
        }
        listOfBannedNames = bannedNamesList
        print(listOfBannedNames)
        completion(listOfBannedNames) // - that will wait until the list of names arrives
    })
}

Then use the function:

makeRequestToFirebase() { names in
    print(names)
    workWithNames(names)
}

Now you can use it however you want, for example:

func workWithNames(names: [String]) {
    for name in names {
        if name == "Alexander" {
            print("One more Alexander found")
        }
}

Also please learn more about escaping closures in Swift.

Upvotes: 2

Related Questions