-3

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 Answers3

0

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • how can I fix it. Please advise because I don't know the solution – James Johnson Jun 25 '17 at 22:27
  • "Solution" to _what_? I don't know what you want to do — because you have not told me. You have shown only a snippet of your code, and none of the code that you have shown in that snippet is problematic in any way. It all behaves exactly as expected. That is why your question is being downvoted; there's no problem so there's nothing to ask a question about. – matt Jun 26 '17 at 16:41
0

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

Loadar
  • 21
  • 1
  • no I checked before hand and found that the data was in the file inside the fullResolutionImageData function but outside that function the array was nil. Below what matt said is right but I don't know how to fix it. – James Johnson Jun 26 '17 at 14:02
  • If that so, you can try move the definition of array "files" outside of the Dispatch closure to keep the lifecycle – Loadar Jun 27 '17 at 02:28
0

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)

Amber
  • 21
  • 3