Reputation: 53
I am new to Swift and am trying to make a function that simply returns the number of photos in your screenshot album using fetchAssetCollections
I have
func getNumScreenshots() -> Int {
let collection:PHFetchResult =
PHAssetCollection.fetchAssetCollections(with: .album, subtype:.smartAlbumScreenshots, options: nil)
return collection.count
}
However, this is always returning 3, and I'm not sure why (I have 600 screenshots on my iPhone).
Upvotes: 4
Views: 1705
Reputation: 11766
You can use a predicate like this :
let options = PHFetchOptions()
options.predicate = NSPredicate(format: "(mediaSubtype & %d) != 0", PHAssetMediaSubtype.photoScreenshot.rawValue)
let screenshots = PHAsset.fetchAssets(with: .image, options: options)
print("screenshots count: \(screenshots.count)")
Upvotes: 0
Reputation: 494
In Swift 4 there is a very quick way to fetch PHAssets
of just ScreenShots, without messy if else
s:
Swift 4 :
let sc_Fetch = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: **.smartAlbumScreenshots**, options: nil).firstObject!
let sc_Assets = PHAsset.fetchAssets(in: sc_Fetch , options: nil)
print("All ScreenShots Count : " , sc_Assets.count)
Upvotes: 1
Reputation: 7419
You can try with this:
let albumsPhoto:PHFetchResult<PHAssetCollection> = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
albumsPhoto.enumerateObjects({(collection, index, object) in
if collection.localizedTitle == "Screenshots"{
let photoInAlbum = PHAsset.fetchAssets(in: collection, options: nil)
print(photoInAlbum.count) //Screenshots albums count
}
})
Note: Use this code is Swift 3
Upvotes: 7