I am using "PHAsset" for fetching camera roll assets. I am using
PHAsset.fetchAssetsWithMediaType(.Image, options: options)
for fetching all gallery images. But I want to fetch all Images and Videos at a same time and show in a collection view (like Instagram camera view).
Can any one please tell me how can I do it?
Actual Solution (swift 4 and probably swift 3): In your viewDidLoad or where ever is right for your case call checkAuthorizationForPhotoLibraryAndGet()
private func getPhotosAndVideos(){
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d || mediaType = %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
print(imagesAndVideos.count)
}
private func checkAuthorizationForPhotoLibraryAndGet(){
let status = PHPhotoLibrary.authorizationStatus()
if (status == PHAuthorizationStatus.authorized) {
// Access has been granted.
getPhotosAndVideos()
}else {
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if (newStatus == PHAuthorizationStatus.authorized) {
self.getPhotosAndVideos()
}else {
}
})
}
}
1) Make sure mediaType = %d is used instead of mediaType == %d
2) Make sure you actually have authorization and can access the photo library, otherwise it would fail silently.
Fell free to use NSPredicate
.
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType == %d || mediaType == %d",
PHAssetMediaType.image.rawValue,
PHAssetMediaType.video.rawValue)
fetchOptions.fetchLimit = 100
let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
This might work for you:
let allMedia = PHAsset.fetchAssetsWithOptions(fetchOptions)
let allPhotos = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
let allVideo = PHAsset.fetchAssetsWithMediaType(.Video, options: fetchOptions)
print("Found \(allMedia.count) media")
print("Found \(allPhotos.count) images")
print("Found \(allVideo.count) videos")
The Media types are defined as:
public enum PHAssetMediaType : Int {
case Unknown
case Image
case Video
case Audio
}
Because it's not an OptionSetType
you can't use it like a bitfield and combine them for PHAsset.fetchAssetsWithMediaType
, but the PHAsset.fetchAssetsWithOptions
might work for you. Just be prepared to filter out Audio types from the result set.
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