Function doesnt wait download Picture with Alamofire in Swift

774 Views Asked by At

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)
2

There are 2 best solutions below

1
On BEST ANSWER

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")
    }
}
0
On

You set the image directly after starting the asynchronous download, when it of course is still nil. The point of using a callback as you do in your code is that you only can use a requested resource once the callback gets called; so you should move the code that's using the image into the callback block.