0

I am downloading images from an API (multiple urls into a CollectionView). Everything works fine until a link is not reachable and the app crashes. How can i download from the links that are reachable but skip the ones that are not?

    guard let url = URL(string: self.photos[indexPath.item]) else { return cell }
    cell.imageView.image = nil
    
    DispatchQueue.global().async {
        guard let image = UIImage(data: try! Data(contentsOf: url)) else { return }
                
        let dataCompress = image.compress(to: 1000)
        if let image = UIImage(data: dataCompress) {
            DispatchQueue.main.async {
                cell.imageView.image = image
                self.photos.append(image)
            }
        }
    }
    return cell
}

"Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=256 "The file “665x10002.jpg” couldn’t be opened." UserInfo={NSURL=https://"*************}

Current code crashes when a link happens to be unreachable. Any help is appreciated.

Redstain
  • 157
  • 2
  • 10
  • 1
    try! will always crash at some point - you should always use optionals for this sort of thing - there's a good answer here https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift – Russell Sep 01 '20 at 15:04

2 Answers2

1
  1. As already mentioned, you should not be using try!.
  2. You should never be using Data(contentsOf:) to fetch data from a remote server. This is explicitly mentioned in the documentation for that initializer.

Instead, you should use

URLSession.shared.dataTask(with: url) { data, response, error in
  // process the data or handle the error
}
Rudedog
  • 4,323
  • 1
  • 23
  • 34
0
guard let image = UIImage(data: try? Data(contentsOf: url)) else { return }

The crash is occurring because you're using ! to force unwrap your try statement. Force unwrapping is dangerous (for this reason) and should only be used when you're certain that the information will be there, otherwise the app will crash. Replace ! with ?, as above, to gracefully return when the contents of the URL is not available.

teacup
  • 624
  • 1
  • 8
  • 18