1、检索音视频

  1. PHFetchOptions *allPhotosOptions;
  2. @property (nonatomic, strong) PHFetchResult *assetsFetchResults;
  3. if (allPhotosOptions == nil) {
  4. allPhotosOptions = [[PHFetchOptions alloc] init];
  5. allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
  6. }
  7. self.assetsFetchResults = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];

其中assetsFetchResults存储了所有的图片信息,PHAssetMediaTypeImage为搜索图片的类型,同样的搜索其他类的可以根据

  1. typedef NS_ENUM(NSInteger, PHAssetMediaType) {
  2. PHAssetMediaTypeUnknown = 0,
  3. PHAssetMediaTypeImage = 1,
  4. PHAssetMediaTypeVideo = 2,
  5. PHAssetMediaTypeAudio = 3,
  6. } NS_ENUM_AVAILABLE_IOS(8_0);
2、获取图片UIImage

  1. [[PHCachingImageManager defaultManager] requestImageForAsset:asset
  2. targetSize:AssetGridThumbnailSize
  3. contentMode:PHImageContentModeAspectFill
  4. options:nil
  5. resultHandler:^(UIImage *result, NSDictionary *info) {
  6. // Set the cell's thumbnail image if it's still showing the same asset.
  7. if ([cell.representedAssetIdentifier isEqualToString:asset.localIdentifier]) {
  8. cell.thumbnailImage = result;
  9. }
  10. }];
asset为assetsFetchResults中的一个PHAsset,targetSize是获取图片的大小,这个根据你显示的方式设置,如果需要获取图片其他信息比如标题可以采用
[phAsset valueForKey:@"filename"];

3、播放视频

  1. -(void)setVideoAsset:(PHAsset *)videoAsset
  2. {
  3. _videoAsset = videoAsset;
  4. [[PHImageManager defaultManager] requestPlayerItemForVideo:_videoAsset options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
  5. self.currentItem = playerItem;
  6. [self.player replaceCurrentItemWithPlayerItem:self.currentItem];
  7. [self.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
  8. }];
  9. }