PruitIgoe
PruitIgoe

Reputation: 6384

"Cannot convert value of type '()' to UIImage": Swift

I am trying to load a UIImage from a URL and then pass that UIImage back through a closure.

This is the code to get the image:

func getImageFromData(_ imgURL:URL, completion: @escaping imageClosure) {

    print("Download Started")
    getDataFromUrl(url: imgURL) { data, response, error in
        guard let data = data, error == nil else {
            return
        }

        if let thisImage = UIImage(data: data) {
            completion(thisImage)
        }

    }

}

func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
    URLSession.shared.dataTask(with: url) { data, response, error in
        completion(data, response, error)
        }.resume()
}

this is imageClosure

typealias imageClosure = (_ thisImage:UIImage) -> Void

and I am calling as such

let thisImage:UIImage = myAPIManager.getImageFromData(thisImageURL, completion: { (thisImage:UIImage) in

    })

and I get the error on the above line:

Cannot convert value of type '()' to specified type 'UIImage'

Upvotes: 0

Views: 488

Answers (2)

a.masri
a.masri

Reputation: 2469

This funcction getImageFromData not return value

Edit this

let thisImage:UIImage = myAPIManager.getImageFromData(thisImageURL, completion: { (thisImage:UIImage) in

    }) 

To this

myAPIManager.getImageFromData(thisImageURL, completion: { (thisImage:UIImage) in

let myImage:UIImage = thisImage

    })

Upvotes: 0

Alexander
Alexander

Reputation: 63157

Your definition of getImageFromData returns Void (a type whose only member is also called Void, a.k.a the empty tuple, ()). It doesn't return an image.

You need to set the image inside the callback closure, not by assigning the non-existent return value of the function.

Upvotes: 1

Related Questions