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.