iosobjective-ccocoa-touchcompressionalassetslibrary

Can not compress video from ALASSET URL in iOS?


I got video URL from ALASSET thenconvertVideoToLowQuailtyWithInputURL function to compress video but it can not work. I saw after compress, size of video always is 0.

This is function to get video URL from ALASSET:

ALAsset *alasset = [allVideos objectAtIndex:i];
            ALAssetRepresentation *rep = [alasset defaultRepresentation];
            NSString * videoName = [rep filename];

            //compress video data before uploading
            NSURL  *videoURL = [rep url];
            NSLog(@"videoURL is %@",videoURL);


            NSURL *uploadURL = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:videoName] stringByAppendingString:@".mov"]];
            NSLog(@"uploadURL temp is %@",uploadURL);

            // Compress movie first
            [self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:uploadURL handler:^(AVAssetExportSession *session)
             {
                 if (session.status == AVAssetExportSessionStatusCompleted)
                 {
                     // Success
                 }
                 else
                 {
                     // Error Handing

                 }
             }];

            NSString *path = [uploadURL path];
            NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
            NSLog(@"size after compress video is %d",data.length);
        }

Function compress video :

- (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL
                                   outputURL:(NSURL*)outputURL
                                     handler:(void (^)(AVAssetExportSession*))handler
{
    [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset: urlAsset presetName:AVAssetExportPresetLowQuality];
    session.outputURL = outputURL;
    session.outputFileType = AVFileTypeQuickTimeMovie;
    [session exportAsynchronouslyWithCompletionHandler:^(void)
     {
         handler(session);

     }];
}

When I called convertVideoToLowQuailtyWithInputURL function, i didn't see it trigger to handler(session); .

And NSLog(@"size after compress video is %d",data.length); always print "size is 0". Where i went wrong? Please give me some advice. Thanks in advance.


Solution

  • convertVideoToLowQuailtyWithInputURL is an asynchronous method, that is why it takes a completion handler block. Your current logging code is not in the completion handler block, but is after the call to convertVideoToLowQuailtyWithInputURL - this will run before convertVideoToLowQuailtyWithInputURL completes so you will never have a result then.

    Move your logging (and usage) of the compressed video into the completion block.