Isuru Isuru - 3 months ago 27
Swift Question

estimatedAssetCount returns a wrong count

I need to display the camera roll album with the count of images in it. I'm using the below code to get the camera roll album.

let smartCollections = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: nil)
smartCollections.enumerateObjectsUsingBlock { object, index, stop in
if let collection = object as? PHAssetCollection {

I have only 28 images in the camera roll in the Photos app. But the
property returns the value 9223372036854775807!

This only happens for OS created albums like the camera roll. For user created regular albums, the correct value is returned. Am I doing anything wrong or is this a bug?

If it is, is there any other way to get the correct image count?

Answer Source

Should have looked a little longer. Going in to the header file of PHAssetCollection reveals this little piece of info.

These counts are just estimates; the actual count of objects returned from a fetch should be used if you care about accuracy. Returns NSNotFound if a count cannot be quickly returned.

So I guess this is expected behavior and not a bug. So I added this below extension method to get the correct image count and it works.

extension PHAssetCollection {
    var photosCount: Int {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Image.rawValue)
        let result = PHAsset.fetchAssetsInAssetCollection(self, options: fetchOptions)
        return result.count
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download