0

There is I am trying to download image from URL and save it to variable of model. But it's not setting the image. Inside setImage I saw that it's downloading some data. URL's are checked and working. But when I check it for nil it's showing "empty input", "empty output".

let inputImage = UIImageView()
    let outputImage = UIImageView()

    DispatchQueue.main.async {
        let inputURL = URL(string: "someURL")
        let outputURL = URL(string: "someURL")
        inputImage.kf.setImage(with: inputURL)
        outputImage.kf.setImage(with: outputURL)
    }
    let coreDataModel = CoreDataModel()
    
    if let inputImageData = inputImage.image?.pngData()
    {  cloudAnalysisModel.input_image = inputImageData  }
    else
    {  print("empty input")  }
    
    if let outputImageData = outputImage.image?.pngData()
    {  coreDataModel.output_image = outputImageData   }
    else
    {  print("empty output")  }

1 Answers1

0

I think you have not understood how asynchronous programming works. The block or completionHandler (the one that starts with { and ends with }) gets executed after url is called and response is obtained

What I mean to say here is , that block maybe executed at any time and the code after that is executed right away i.e the code from let coreDataModel onwards

So it is obvious that both the inputImageData and outputImageData are going to be null

Now coming to the solutions:

What you could do is:

  1. Shift all the code inside the callback block instead of keeping it outside and show the user some progressbar or UI
  2. Use DispatchGroup which keeps track of the DispatchQueue More info here
gtxtreme
  • 1,830
  • 1
  • 13
  • 25