简体   繁体   中英

Firestore instantiate objects with data recover Swift 5.0

I get all the data from my snapshot and create an object list with the data. My problem: I can't return a list to use my objects in other code functions.

I tried to browse my list to create using my snapshot to implement a new list of objects declared above in my code.

class ViewController: UIViewController {

lazy var usersCollection = Firestore.firestore().collection("ship")
var ships: [MyShip] = []

override func viewDidLoad() {
    super.viewDidLoad()

    getUsers()
   print(ships.count)


}

The getData function:

 func getUsers() {
    usersCollection.getDocuments { (snapshot, _) in

       //let documents = snapshot!.documents
       //  try! documents.forEach { document in

       //let myUser: MyUser = try document.decoded()
       //print(myUser)
        //}

        let myShip: [MyShip] = try! snapshot!.decoded()

        // myShip.forEach({print($0)})


        for elt in myShip {
           print(elt)
            self.ships.append(elt)
        }
        print(self.ships[1].nlloyds)
    }
}

result console

Result in the console:

- my list is not filled return 0
- I print the objects well and I print them well
- I print the ships object[1].nloyds = 555 well in the function 

Your print(ships.count) call in viewDidLoad is printing an empty array because the .getDocuments() method is asynchronous. Try writing getUsers as a closure like this:

func getUsers(completion: @escaping ([MyShip]) -> Void) {
    usersCollection.getDocuments { (snapshot, _) in
        let myShip: [MyShip] = try! snapshot!.decoded()
        completion(myShip)
    }
}

and then use it in the viewDidLoad method like this:

override func viewDidLoad() {
    super.viewDidLoad()

    getUsers() { shipsFound in
        self.ships = shipsFound
        print(self.ships.count)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM