I'm using SDWebImag
e to load images into a UICollectionView
. Then when the user clicks on the image I want to copy it to the Pasteboard
so they can paste it into other apps.
The code I am currently using in the didSelectItemAtIndexPath
method goes back to the web to copy the image. But the image should already be in the user's cache.
How do I use SDWebImage
to grab an image for NSData
?
That way the app will first check the cache for the image. I keep running into DataType
issues when I try to use SDWebImage
.
This is my current code. I want to fix the code in the didSelectItemAtIndexPath
:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let iCell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCollectionViewCell", forIndexPath: indexPath) as! ImageCollectionViewCell
let url = NSURL(string: self.imgArray.objectAtIndex(indexPath.row) as! String)
iCell.imgView.sd_setImageWithURL(url)
return iCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// Change code below to use SDWebImage
let url = NSURL(string: self.imgArray.objectAtIndex(indexPath.row) as! String)
let data = NSData(contentsOfURL: url!)
if data != nil {
UIPasteboard.generalPasteboard().setData(data!, forPasteboardType: kUTTypePNG as String)
} else {
// Do nothing
}
}
SDWebImage has a cache. You can access it with SDImageCache
. There is customization allowed (different namespaces for caches).
let image = SDImageCache.sharedImageCache.imageFromDiskCacheForKey(url!)
if image != nil
{
let data = UIImagePNGRepresentation(image);
}
You have to check if image
is not nil
because the downloads are asynchrone. So user may trigger collectionView:didSelectItemAtIndexPath:
whereas the image hasn't been downloaded yet, and per se not present in the cache.