MarksCode
MarksCode

Reputation: 8576

Return image from asynchronous call

I have a picker view that has images as it's scrollable items. I need to pull those images from my database so I'm getting the Unexptected non-void return value in void function error. Here is my code:

func pickerView(_ pickerView: AKPickerView, imageForItem item: Int) -> UIImage {
    let imgRef = FIRStorage.storage().reference().child("profile_images").child(pets[item])
    imgRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
        // Create a UIImage, add it to the array
        let pic = UIImage(data: data!)
        return pic
    }
}

So I understand why this doesn't work but I'm having a hard time finding out what's the best way to get around this. One solution I can think of is to just set the images to some generic photo until the callback happens, then update the picker view's image to the retrieved image. However, I don't know how to access individual picker view items in order to update its image.

If anybody with some experience can give me advice on how I can achieve my goal of setting these items to the data from an asynchronous call I'd greatly appreciate it!

Upvotes: 1

Views: 331

Answers (1)

KrishnaCA
KrishnaCA

Reputation: 5695

Your function here is an asynchronous function. You have to make use of callbacks in this case. You can rewrite the function in the following way to achieve desired results.

func pickerView(_ pickerView:AKPickerView, imageForeItem item:Int, completion:(_ resultImg: UIImage)->Void) {

    let imgRef = FIRStorage.storage().reference().child("profile_images").child(pets[item])
    imgRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
        // Create a UIImage, add it to the array
        if let pic:UIImage = UIImage(data: data!) {
            completion(pic)
        }
    }
}

This can be called as follows:

self.pickerView(pickerView, imageForeItem: 0) { (image) in
    DispatchQueue.main.async {
      // set resulting image to cell here
    }
}

Feel free to suggest edits to make this better :)

Upvotes: 1

Related Questions