Search code examples
iosphotosframework

Unknown exception when exporting video asset


I have the following code to export video data from Photos:

if (asset.mediaType == PHAssetMediaTypeVideo)
{
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
        exportSession.outputFileType = AVFileTypeQuickTimeMovie;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            [[SharedManager sharedInstance] insertAttachment:exportSession.outputURL forEvent:event];
        }];
    }];
}

This code rises an unidentified exception (with breakpoints disabled) on the line with [exportSession export...] thing. ExportSession is valid, but shows outputFileType = (null) in the log, so I had to set it manually.

I can see the URL of the video, something like file://private.mobile....MOV, it was captured by camera and is stored in the assets catalog (I can watch it with Photos). It has 2 seconds length.

Please, help me out. How to export video file using Photos?

P.S.: Exporting of images using PHImageManager works perfectly fine.


Solution

  • Okay, I've found the issue. It is not said in the documentation, but it is required that outputURL set manually. So the following peace of code (from this answer https://stackoverflow.com/a/20244790/773451) is required:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *outputURL = paths[0];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil];
    outputURL = [outputURL stringByAppendingPathComponent:@"output.mov"];
    // Remove Existing File
    [manager removeItemAtPath:outputURL error:nil];
    exportSession.outputURL = [NSURL fileURLWithPath:outputURL];