将照片中的图像加载到 collection 视图导致错误消息 "Connection to assetsd was interrupted or assetsd died"

Loading of images from Photos to collection view results in error message "Connection to assetsd was interrupted or assetsd died"

我正在尝试将用户相册中的所有图像加载到我的应用程序的 Collection 视图中,但是在加载其中一些之后,该应用程序将自行关闭并 return 返回到主菜单。与XCode的连接也断开了。 这不会发生在模拟器中,而只会发生在我正在测试的 iPhone 4s 中。 崩溃前出现的错误信息,按发生顺序排列,

  1. 收到内存警告
  2. 与 assetsd 的连接中断或 assetsd 死亡。

我已经找到了我认为导致此问题的部分代码。

var imgFetchResult: PHFetchResult!

override func viewDidLoad() {
    super.viewDidLoad()
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

    let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)

    if fetchResult.count > 0
    {
        println("images found ? \(fetchResult.count)")
        self.imgFetchResult = fetchResult
    }
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    println("cellForItemAtIndexPath")
    let cell: PhotoThumbnailCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as PhotoThumbnailCollectionViewCell

    println("indexpath is \(indexPath.item)")

    if( indexPath.item == 0 )
    {
        cell.backgroundColor = UIColor.redColor() //temp placeholder for camera image
    }
    else
    {
        let asset: PHAsset = self.imgFetchResult[indexPath.item] as PHAsset 
        PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
        })
    }

    return cell
}

我认为我需要释放内存但不确定要释放什么。似乎是图像正在加载到 collection 视图的单元格中。

我还发现 collection 视图不超过 4 张图像。在第四张图片之后,崩溃发生了。此外,图像未按顺序加载。

在这行代码中发现了问题

PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
})

参数 targetSize 传递了 PHImageManagerMaximumSize 的值,这是罪魁祸首。我将其更改为 CGSize(width: 105, height: 105) 解决了问题。

根据文档 PHImageManagerMaximumSize

When you use the PHImageManagerMaximumSize option, Photos provides the largest image available for the asset without scaling or cropping. (That is, it ignores the resizeMode option.)

所以,这就说明了问题。我相信如果是单张图片,应该没有问题,但如果是多张图片,设备会 运行 内存不足。

我希望这对其他人有帮助。

正如@winhung 所说,对我来说它也是尺寸。我所做的是将目标大小减少一半,例如:

let asset: PHAsset = self.imgFetchResult[indexPath.item] as PHAsset 
let mytargetSize = CGSize(width: asset.pixelWidth/2, height: asset.pixelHeight/2)

PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: mytargetSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
})