-2

My JSON response has many data including images what i want is to show the texts ( because it's downloaded so fast ) and in the background the images download and appear when it complete

here is my code to handle the image in my cell in cellForRowAt func

    if let imgeArray = self.myResponse[indexPath.row]["photos"] as? [[String:Any]] {
        if let photoUrl = imgeArray[0]["Url"] as? String {

            if let url = NSURL(string: "https:serverName/Pics/\(photoUrl)"){

                if let data = NSData(contentsOf: url as URL) {

                    cell?.Image.contentMode = .scaleAspectFit
                    cell?.Image.image = UIImage(data: data as Data)
                }
            }
        }

    }

it works fine but takes time any help ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
alfhd
  • 35
  • 6
  • 3
    Please search before asking. The business of supplying images to table cells asynchronously has been explained many times. – matt Oct 28 '18 at 06:18
  • so sorry bro but i already search about that please share the link – alfhd Oct 28 '18 at 06:23
  • 1
    You are strongly discouraged from loading data from a remote URL with synchronous `Data(contentsOf` even in a background thread. Use an asynchronous download manager. And don’t use `NS` classes in Swift if there are native counterparts (`Data`, `URL`). – vadian Oct 28 '18 at 07:08

1 Answers1

-1

First call DispatchQueue.global(qos: .background).async after download image then call DispatchQueue.main.async then set image in image view.

cell?.Image.contentMode = .scaleAspectFit
DispatchQueue.global(qos: .background).async {

    if let url = NSURL(string: "https:serverName/Pics/\(photoUrl)"){

        if let data = NSData(contentsOf: url as URL) {

            DispatchQueue.main.async {
                cell?.Image.image = UIImage(data: data as Data)
            }

        }
    }

}
Sabbir Ahmed
  • 351
  • 1
  • 13
  • same result there is delaying and the whole details come together – alfhd Oct 28 '18 at 06:49
  • 1
    Downloading an image takes time and depends on a number of factors such as the user's connection and the size of the image. If it's taking too long, you should look into compressing the images, or caching them locally after the first download. – Connor Neville Oct 28 '18 at 07:08
  • @SabbirAhmed it's work but shows me error for cell?.image.contentMode the error is ( UIView.contentMode must be used from main thread only ) can you please update your answer so i can mark it as the perfect one ? thanx in advance – alfhd Oct 28 '18 at 08:40
  • it's working perfectly in my project, but you get error UIView.contentMode must be used main thread so you move background thread to main thread, please check my answer updated it – Sabbir Ahmed Oct 28 '18 at 09:15