I am looping over a couple of urls but only some will give back an image. The other ones are just empty. The urls which give back an image can change daily which is why I want to loop over all urls. I am wondering if loading an empty url takes a significant amount of the users data and would be "bad programming".
I do not think my code is necessary to answer the question but here it is in case it helps.
for index in 1..<32{
let url = URL(string: "https://jarisstoriesphotographyphoto.files.wordpress.com/2020/06/menu\(index).png")!
// 1.
frame.origin.x = scrollView.frame.size.width * CGFloat(index-1)
frame.size = scrollView.frame.size
// 2.
let imageView = UIImageView(frame: frame)
getImage(withURL: url) { image in
imageView.image = image
self.scrollView.addSubview(imageView)
}
}
my get image function
func getImage(withURL url:URL, completion: @escaping (_ image:UIImage?)->()) {
if let cachedVersion = cache.object(forKey: url.absoluteString as NSString) {
completion(cachedVersion.image)
} else {
downloadImage(withURL: url, completion: completion)
}
}
My downloading function
func downloadImage(withURL url:URL, completion: @escaping (_ image:UIImage?)->()) {
let dataTask = URLSession.shared.dataTask(with: url) { data, responseURL, error in
var downloadedImage:UIImage?
if let data = data {
downloadedImage = UIImage(data: data)
}
if downloadedImage != nil {
let cacheImage = ImageCache()
cacheImage.image = downloadedImage
self.cache.setObject(cacheImage, forKey: url.absoluteString as NSString)
}
DispatchQueue.main.async {
completion(downloadedImage)
}
}
dataTask.resume()
}
A simple check would be to check what the "empty" response returns.
Using curl on the command line will tell you the sizes of the request (what your users are sending), and the headers and download size of the response.
curl --compressed -w '%{size_request} %{size_header} %{size_download}' http://example.com/
That will output 3 numbers (in bytes) after the response data. Testing against an example of the URL in your code sample that returns 404
outputs 160 263 761
.
So roughly speaking, each empty URL uses ~1.15 kB of data (this depends on the exact compression used, and other variables, depending on the server).