I am trying to load all the images from the user's Photo album into my app's Collection View but after a loading a few of them, the app will close itself and return back to the main menu. The connection with XCode is also disconnected. This does not happen in the simulator but only the iPhone 4s that i am testing with. The error messages that appear before it crashes is, in order of occurrence,
I have picked up several portions of the code that i believe is causing this problem.
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
}
I believe i need to release memory but not sure what to. It seems to be the images that are being loaded into the cells of the collection view.
I have also found that the collection view does not go beyond 4 images. After the 4th image, the crash happens. Also, the images are not loaded in order.
The problem was found in the this line of code
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
})
The parameter, targetSize
was passed the value of PHImageManagerMaximumSize
which was the culprit. I changed it to CGSize(width: 105, height: 105)
resolved the issue.
According to the documentation 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.)
So, this explains the problem. I believe if it was a single image, it should not be a problem but if it was many images, the device would run out of memory.
I hope this helps other people.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With