I have adopted an iOS project and need to make add an image method to an object. I was thinking something like this. However, how would I declare the image
method to return a UIImage? or is this even possible?
From a larger perspective, these items will be in a UICollection view so I need to load the image to determine the height of a custom UICollectionViewCell.
class Item {
var imageURL = "https://s3-us-west-1.amazonaws.com/bucket/images/26882/abc.jpg?1477323919"
// probably need to change this
func image() -> UIImage {
URLSession.shared.dataTask(with: NSURL(string: imageURL)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
return image
})
}).resume()
}}
}
edit #1
here's the consumer for this call - not sure if I can adjust this to make it ammenable to an async call in order to get the image. It might be easier to send metadata down in the JSON call rather than computing it via this async call.
extension MasterViewController: MosaicLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, heightForImageAtIndexPath indexPath: IndexPath, withWidth width: CGFloat) -> CGFloat {
let item = items[indexPath.item]
let image = item.image() // need to get this height
let boundingRect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
let rect = AVMakeRect(aspectRatio: image.size, insideRect: boundingRect)
return rect.height
}