Quickly extract images and videos from the camera

I use "PHAsset" to retrieve the resources of a camera clip. I use

PHAsset.fetchAssetsWithMediaType(.Image, options: options) 

to select all gallery images. But I want to get all the images and videos at the same time and show them as a collection (for example, viewing an Instagram camera).

Can someone tell me how can I do this?

+5
source share
3 answers

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") 

Media types are defined as:

 public enum PHAssetMediaType : Int { case Unknown case Image case Video case Audio } 

Since this is not an OptionSetType , you cannot use it as a PHAsset.fetchAssetsWithMediaType and combine them for PHAsset.fetchAssetsWithMediaType , but PHAsset.fetchAssetsWithOptions may work for you. Just be prepared to filter out the types of audio from the result set.

+3
source

You cannot 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) 
+3
source

Actual solution (fast 4 and probably fast 3): In your viewDidLoad or where ever 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 that you really have authorization and you can access the photo library, otherwise it will fail.

+2
source

All Articles