Best place to put dispatch in CollectionView with Firebase

1

I'm breaking my head with an application based on some examples from Brian Lets Build That App , tailoring your videos to my need. I'm downloading some Firebase images and updating a collectionview. What I'm having problem is not knowing the best place to put the completionHandler([appPhotos]) function, I've tried everything ....

ControllerDetail.swift

AppPhotos.fetchePhotosApp(pacienteID: self.paciente_key) { (appPhotos) in
        self.appPhotos = appPhotos
        self.collectionView?.reloadData()
        print("CALLING")

    }

Models.swift

static func fetchePhotosApp(pacienteID: String, completionHandler: @escaping ([AppPhotos]) -> ()) {

    let user = FIRAuth.auth()?.currentUser
    let appPhotos = AppPhotos() //
    var apps = [App]() //

    FIRDatabase.database().reference().child((user?.uid)!).child("photos").child(pacienteID).observeSingleEvent(of: .value, with: { (snapshot) in
        var newPhotos = [Photo]()

        for itemSnapShot in snapshot.children {
            let item = Photo(snapshot: itemSnapShot as! FIRDataSnapshot)
            newPhotos.append(item)
        }

        let photos = App()//

        var dataConsulta = [Int]()

        for index in 0..<newPhotos.count {
            if !dataConsulta.contains(newPhotos[index].data_consulta!) {
                dataConsulta.append(newPhotos[index].data_consulta!)

            }

            appPhotos.data_consulta = newPhotos[index].data_consulta_text

            let url = URL(string: newPhotos[index].photo_original!)


            URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
                if error != nil {
                    print(error!)
                    return
                }

                    photos.photo_original = UIImage(data: data!)
                    apps.append(photos)
                    print("DOWNLOADED")

            }).resume()

        }

        print("OUT FOR")

        appPhotos.apps = apps

        DispatchQueue.main.async(execute : {
            completionHandler([appPhotos])
        })

    }, withCancel: nil)
}

Result

OUT FOR
CALLING
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED

The result should be:

DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
OUT FOR
CALLING

or

OUT FOR
CALLING
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
DOWNLOADED
CALLING

Thanks for helping.

    
asked by anonymous 02.05.2017 / 20:52

0 answers