I have an array of strings containing the URL of the photo images. I have a Custom Layout and I need to convert an array of strings to UIImage
, and then get their size.
Here is my code:
extension PhotoFeedViewController: CustomLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, sizeOfPhotoAtIndexPath indexPath: IndexPath) -> CGSize {
let bodyImage = UIImageView()
let url = URL(string: collectionPhotos[indexPath.row])
let data = try? Data(contentsOf: url!)
// DispatchQueue.main.async {
if let imageData = data {
bodyImage.image = UIImage(data: imageData)
}
// }
return bodyImage.image?.size ?? CGSize(width: 100, height: 100)
}
}
This code works , but there is a problem. When I launch the app, the images appear after all the images are loaded, because everything is synchronous.
If you uncomment:
DispatchQueue.main.async {
The returned property is empty and does not see the code that is in the Dispatch block
How do I make this code asynchronous so that the size of the images is passed asynchronously and the user doesn't wait for the full load of images to be displayed on the screen? Without the use of libraries.
Sorry for my English.