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.
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()
}
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........... :)