I try to download picture with Alamofire and this image must be append to custom class. But I didnt do that. Image is downloaded with async and i didnt fix this issue. Where is my mistake ?
Image always return nil
// MARK: CUSTOM FUNCTION
import UIKit
import Alamofire
import AlamofireImage
class DownloadPhotoWAlamofire {
func download(imageUid:String , completion : @escaping (UIImage) -> () ) {
let url = "\(Config.fileService)file?uid=\(String(describing: imageUid))"
print("URL \(url)")
Alamofire.request(url, method: .get ).responseImage { response in
print("Image Response \(response)")
let image = response.result.value
completion(image!)
}
}
}
// MARK : IN VIEWCONTROL
guard let objectElement = o as? [String:Any] else {return}
let managerName = objectElement["managerName"] as? String
let managerAvatarUid = objectElement["managerProfilePictureFileUid"] as? String
let assistantsOfDiariesUid = objectElement["assistantsOfDiariesUid"] as? String
var image:UIImage? = nil
if managerAvatarUid != nil {
DownloadPhotoWAlamofire().download(imageUid: managerAvatarUid!, completion: { (imageD) in
image = imageD
})
}
let e = AssistantInviteElement(managerName: managerName!, managerAvatarUid: managerAvatarUid, assistantsOfDiariesUid: assistantsOfDiariesUid!,avatarImage:image)
self.managerList.append(e)
Change it to :
if managerAvatarUid != nil {
DownloadPhotoWAlamofire().download(imageUid: managerAvatarUid!, completion: { (imageD) in
let image = imageD
let e = AssistantInviteElement(managerName: managerName!, managerAvatarUid: managerAvatarUid, assistantsOfDiariesUid: assistantsOfDiariesUid!,avatarImage:image)
self.managerList.append(e)
})
}
As downloading is asynchronous call and you this line is executing before image is downloaded :
let e = AssistantInviteElement(managerName: managerName!, managerAvatarUid: managerAvatarUid, assistantsOfDiariesUid: assistantsOfDiariesUid!,avatarImage:image)
at that time image is nil. So call it only when you have image downloaded and it should work.
Also don't unwrap optional with "!", do a if let/ guard let. So change Almofire code to :
Alamofire.request(url, method: .get ).responseImage { response in
print("Image Response \(response)")
if let image = response.result.value {
print("image downloaded: \(image)")
completion(image)
} else {
print("Image is nil")
}
}