0

i want to load data in array when i go in the view controller.When i print the array, it is empty but if i use a refresh and print again the array, he is loaded.It is the code :

var information = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    loadinformation()
    print(information)
}

func loadinformation() {
    let ref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    let prof = ref.child("users").child(uid!).child("interess")
    prof.observeSingleEvent(of: .value,with: { (snapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let name = dict["FullName"] as! String
            self.information.append(name)
        }
    })


}

1 Answer 1

1

This line

prof.observeSingleEvent(of: .value,with: { (snapshot) in

is asynchronous which means it's doesn't run as the serial flow of code , you need to print it here

let name = dict["FullName"] as! String
self.information.append(name)
print(self.information)

//

Or use completion

func loadinformation(completion:@escaping(_ arr:[String]?) -> Void ) {
    var arr = [String]()
    let ref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    let prof = ref.child("users").child(uid!).child("interess")
    prof.observeSingleEvent(of: .value,with: { (snapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let name = dict["FullName"] as! String
            arr.append(name)
            completion(arr)
        }
        else {
            completion(nil)
        }
    })

}

Call

loadinformation { (result) in
  print(result)
  if let content = result {
    self.information = content 
    self.collectionView.reloadData()
  }
}
Sign up to request clarification or add additional context in comments.

9 Comments

i have a collection view where in every cell i have a label where the text is the value of array[indexpath.row]
i hide the other code because my problem is the array
reload the collection inside the callback
unnder self.information.append... i write collectionview.reloadData()
try the edit it should refresh the collection , your old reload ran before the result returns
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.