Search code examples
iosobjective-cuiimageavplayeritem

Convert AVPlayerItem to NSData


I am trying to achieve a simple task like converting a UIImage to NSData, for AVPlayerItem that is returned to me when I select a video from the PHImageManager. What might be an equivalent of the UIImagePNGRepresentation to convert video in data:

PHVideoRequestOptions *videoRequestOptions = [[PHVideoRequestOptions alloc] init];
videoRequestOptions.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
videoRequestOptions.version = PHVideoRequestOptionsVersionOriginal;

[[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:videoRequestOptions resultHandler:^(AVPlayerItem *item, NSDictionary *info)
            {
                //?
            }];

Whereas the UIImage goes like this:

[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:imageRequestOptions resultHandler:^(UIImage *result, NSDictionary *info)
{
     NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(result)]; //<==THIS
}

Solution

  • The solution is to get the URL from the AVPlayerItem asset, then create NSData from that URL:

    PHAsset *asset = ...
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    [[PHImageManager defaultManager] requestPlayerItemForVideo:asset options:options resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
                    NSURL *fileURL = [(AVURLAsset *)playerItem.asset URL];
                    NSData *videoData = [NSData dataWithContentsOfURL:fileURL];
                    NSLog(@"tmpData Size: %lu",tmpData.length);
    }];
    

    and another way is to use 'requestAVAssetForVideo:asset' ....

    PHFetchOptions *fetchOption = [[PHFetchOptions alloc]init];
    if ([fetchOption respondsToSelector:@selector(setFetchLimit:)]) {
        [fetchOption setFetchLimit:1];
    }
    PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[@"<Video-localIdentifier>"] options:fetchOption].firstObject;
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc]init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset
                                                    options:options
                                              resultHandler:
     ^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
         AVURLAsset *urlAsset = (AVURLAsset *)asset;
         NSData *videoData = [NSData dataWithContentsOfURL:urlAsset.URL];
    
         if (videoData) {
             NSLog(@"videoData Size: %lu", videoData.length);
         }
    
     }];