使用SDWebImage将图像作为NSData复制到Pasteboard

时间:2016-08-25 16:23:50

标签: swift nsdata sdwebimage

我使用SDWebImag e将图片加载到UICollectionView。然后,当用户点击图片时,我想将其复制到Pasteboard,以便他们将其粘贴到其他应用中。

我目前在didSelectItemAtIndexPath方法中使用的代码会返回到网络以复制图像。但是图像应该已经存在于用户的缓存中。

如何使用SDWebImage抓取NSData的图片?

这样,应用程序将首先检查图像的缓存。当我尝试使用DataType时,我一直遇到SDWebImage个问题。

这是我目前的代码。我想修复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
    }
}

1 个答案:

答案 0 :(得分:0)

SDWebImage有一个缓存。您可以使用SDImageCache访问它。允许自定义(缓存的不同命名空间)。

let image = SDImageCache.sharedImageCache.imageFromDiskCacheForKey(url!)‌
if image != nil
{
    let data = UIImagePNGRepresentation(image);
}

您必须检查image是否不是nil,因为下载是异步的。因此,用户可能会触发collectionView:didSelectItemAtIndexPath:而图像尚未下载,而且本身不会出现在缓存中。