-1

How to return downloadedImage from beginGetImageRequest.

func beginGetImageRequest() {

    if let imagePath = thumbPath {
        request = Alamofire.request(.GET, imagePath).response(completionHandler: { (_, _, imageData, error) -> Void in
            if error != nil {
                NSLog("Error downloading thumbnail image: \(error)")
            } else {
                if let downloadedImage = UIImage(data: imageData!) {
                    self.imageView.image = downloadedImage
                }
            }
        })
    }
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
Balla Joe
  • 25
  • 1
  • 8
  • 1
    You cannot return anything from `beginGetImageRequest`. The fetching of the image is _asynchronous_. Search on that word; this is the most frequently asked and answered form of question in all iOS programming. – matt Aug 22 '17 at 01:49

1 Answers1

0

Misunderstood the request, and I edit it agian:

func beginGetImageRequest(completion:(_ image:UIImage)->()){

    if let imagePath = thumbPath {
        request = Alamofire.request(.GET, imagePath).response(completionHandler: { (_, _, imageData, error) -> Void in
            if error != nil {
                NSLog("Error downloading thumbnail image: \(error)")
            } else {
                if let downloadedImage = UIImage(data: imageData!) {
                    completion(downloadedImage)
                }
            }
        })
    }
}

When you call the method:

beginGetImageRequest { (image:UIImage) in
        // code you need
    }
  • This will work, but you could also create a pattern where the parameter you pass to the completion is an enum with success and fail values. On success, pass the image, on fail, pass the error object. Just depends on what the caller needs. – David Lari Aug 22 '17 at 01:53
  • @DavidLari I can't agree with your comment more.Of course, We need to judge whether it is sucessfully or failed. –  Aug 22 '17 at 02:02
  • @david Lari, the question is how to pass it in swift. – Balla Joe Aug 24 '17 at 15:58
  • @user205265, can you elaborate on your comment? Not sure what point you are trying to make. Thanks! – David Lari Aug 24 '17 at 16:50
  • Like if you could give an example like Omni Ringo, it will be great. – Balla Joe Aug 24 '17 at 20:22