Search code examples
iosobjective-cavplayeravkit

Getting url for PHAsset


I am using a custom image picker to pick a time lapse and I want to get the url of the picked time lapse so I can then play the time lapse.

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
for (PHAsset *asset in assets) {



    NSURL *url = [NSURL URLWithString: assetURLgoesHere];
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
    AVPlayer *videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];


    [videoPlayer play];

}

[self dismissViewControllerAnimated:YES completion:NULL];
}

This is what I have at the moment but I need to get the url of the asset.

I usually use swift but this custom image picker is written in objective-c. so I am a bit of a objective-c noob

Updated code

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
for (PHAsset *asset in assets) {

    - (PHImageRequestID)requestAVAssetForVideo:(PHAsset *)asset options:(PHVideoRequestOptions *)options resultHandler:(void (^)(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info))resultHandler

    NSURL *url = [NSURL URLWithString: asset];
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
    AVPlayer *videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];


    [videoPlayer play];

}

[self dismissViewControllerAnimated:YES completion:NULL];
}

Solution

  • You should use PHImageManager.

    Use the class's sharedInstance and call this method with your PHAsset, options, and a completion block handler:

    - (PHImageRequestID)requestAVAssetForVideo:(PHAsset *)asset options:(PHVideoRequestOptions *)options resultHandler:(void (^)(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info))resultHandler
    

    The handler will give you an AVAsset you should use for your AVPlayerItem, as opposed to a URL.

    Example:

    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
      // Use the AVAsset avAsset
      AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
      AVPlayer *videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];
    }];
    

    Beware its likely asynchronous which will interfere with your application flow further.