1

I am using a page control with a scroll view and want to add downloaded images to the scroll view until the provided link does not download an image anymore. Right now, the link downloads an image until the index is not greater than 7 but the loop still goes on. Apparently it does not return an error, when the url can be still loaded although there is no image to download. This is what I get when I paste the url manually in a browser with an index greater than 7.

enter image description here

This is the code I used. I would like to know if there is a way to test if actual an image was downloaded.

var test = 15

func setupScreens() {
        for index in 1..<test {
                // 1.
            frame.origin.x = scrollView.frame.size.width * CGFloat(index - 1)
            frame.size = scrollView.frame.size

                // 2.
            let imageView = UIImageView(frame: frame)


            let urlSession = URLSession(configuration: .default)
            let url = URL(string: "https://jarisstoriesphotographyphoto.files.wordpress.com/2020/06/menu\(index).png")!

            // Create Data Task

            let dataTask = urlSession.dataTask(with: url) { [weak self] (data, _, error) in
                if let error = error {
                    print(error)
                    self?.test = 0 // should end the loop
                }
                if let data = data {
                    DispatchQueue.main.async {
                        // Create Image and Update Image View
                        imageView.image = UIImage(data: data)
                        self?.scrollView.addSubview(imageView)
                    }
                }
            }
            // Start Data Task
            dataTask.resume()

        }
JPJerry5
  • 107
  • 10
  • Don't you an an error when it's happening (value = 7 as you states)? Or maybe `UIImage(data: data)` returns nil. Also, you know that your image download is asynchrone (very important here), so you could add the image no in the order you think of? Why not use a UIStackView instead? – Larme Jun 19 '20 at 11:10
  • I don't get an error in Xcode. It only shows me the error when paste the url manually in the browser, but I need to get this error into Xcode. It does not matter really if the images are in order or not and what would I do with UIStackView. Sorry if that's a dumb question. This is my first app. – JPJerry5 Jun 19 '20 at 11:17

1 Answers1

2

You can simply check like this before setting the image in your code:

DispatchQueue.main.async {
  if let image = UIImage(data: data) { //Image is available in the url
     imageView.image = image
     self?.scrollView.addSubview(imageView) 
  }else {
     print("Image not available in this url")
  }
}

Keep Coding........... :)

Krishna Raj Salim
  • 7,331
  • 5
  • 34
  • 66