how can I append file to array in block

366 Views Asked by At

I have files I'm appending to an array and I'm doing it inside of a block but the files won't append to the array. I checked if the files were empty and they were not so that is not the problem. I really need help. I've been stuck fir six hours. ImageSource is api for image data off github. Cheers.

    DispatchQueue.global(qos: .background).async {
        () -> Void in

        var files : [PFFile] = [] 
        var photos2: [ImageSource]?
      for i in 0..<13 {
                let indexpath = IndexPath(item: i, section: 0)
                photos2?[indexpath.row].fullResolutionImageData(completion: { (Data) in
                    if let imageData = Data, let image = UIImage(data: imageData), let data = UIImageJPEGRepresentation(image, 1.0){
                    let file = PFFile(data: data)

                            files.append(file!)

                    }
                })
        }
  }
3

There are 3 best solutions below

2
matt On

The files are being appended to the array — namely, to files. But files is a local variable, so after the block runs, it vanishes. If you have some other array elsewhere, or if you are trying to access the value of files outside of the asynchronous block, that's going to fail.

2
Loadar On

It seems that the Array "photos2" is nil, so the function "fullResolutionImageData(completion:)" did nothing

2
Amber On

You need to declare your array outside of the closure so that it exist outside of the closure's scope. At the top of your view controller create an array property (var files = []) and then within the closure call

self.files.append(whatever you are appending)