This feels like a simple error that I'm just not understanding. I'm trying to call my downloadImage()
function on cell.profileImageView
(UIImageView) yet I'm receiving an error stating:
Cannot convert value of type '(status: Bool, image: UIImageView?)' to expected argument type '((status: Bool, image: UIImageView?)) -> Void'
How do call the downloadImage()
as a method for cell.profileImageView.downloadImage()
? The downloadImage()
function and and tableView()
function containing where the error occurs are below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EmployeeTableViewCell", for: indexPath) as! EmployeeTableViewCell
let employeeData = viewModel.employees[indexPath.row]
cell.nameLabel.text = employeeData.fullName
cell.teamLabel.text = employeeData.teamName " Team"
cell.emailLabel.text = employeeData.emailAddress
// if employeeData.smallPhotoUrl != nil {
// cell.profileImageView.(urlString: employeeData.smallPhotoUrl!)
// }
// cell.profileImageView.downloadImage(URLString: employeeData.smallPhotoUrl)
cell.profileImageView!.downloadImage(from: employeeData.smallPhotoUrl!, with: ((status: true, image: cell.profileImageView!)))
return cell
}
func downloadImage(from URLString: String, with completionHandler: @escaping (_ response: (status: Bool, image: UIImageView? ) ) -> Void) {
guard let url = URL(string: URLString) else {
completionHandler((status: false, image: nil))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil else {
completionHandler((status: false, image: nil))
return
}
guard let httpURLResponse = response as? HTTPURLResponse,
httpURLResponse.statusCode == 200,
let data = data else {
completionHandler((status: false, image: nil))
return
}
let image = UIImageView()
completionHandler((status: true, image: image))
}.resume()
}
}
CodePudding user response:
First of all a completion handler is not used for passing data to the method. It's used for retrieving data from a method call after it completes it's work. So you either need to call it as:
cell.profileImageView!.downloadImage(
from: employeeData.smallPhotoUrl!,
with: { status, image in
/// Do what you want with the status or the image values
})
For example when you call completionHandler((status: false, image: nil))
from the downloadImage method the status will be false and image will be nil in the above code.
From what I understand you don't need a completion handler here. You just need a method to set the image to the image view. So changing the implementation to this might work for you:
func downloadImage(from URLString: String, to imageView: UIImageView) {
/// Download the image as you do and once you get the data value
imageView.image = UIImage(data: data)
}
Then you can download the image and set it like this:
cell.downloadImage(from: employeeData.smallPhotoUrl!, to: cell.profileImageView!)