Nicola Miotto
Nicola Miotto

Reputation: 3696

Copy downloaded video to camera roll

Even though it looks like a simple procedure, it's by now 3 hours I'm trying without success. I am probably missing something really stupid.

So, I have this app downloading videos from the Internet. The videos are correctly stored locally because I can play them providing the local url. But, I can't succeed in copying the videos to the camera roll. Here is what I do:

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    ALAssetsLibraryWriteVideoCompletionBlock videoWriteCompletionBlock =
    ^(NSURL *newURL, NSError *error) {
        if (error) {
            NSLog( @"Error writing image with metadata to Photo Library: %@", error );
        } else {
            NSLog( @"Wrote image with metadata to Photo Library %@", newURL.absoluteString);
        }
    };

    NSLog(@"file %@", localPath);
    NSURL *url = [NSURL fileURLWithPath:localPath isDirectory:NO];
    [library writeVideoAtPathToSavedPhotosAlbum:url
                                completionBlock:videoWriteCompletionBlock];

But the output I get is:

2013-07-24 00:13:32.094 App[1716:907] file /var/mobile/Applications/70C18C4E-9F97-4A6A-B63E-1BD19961F010/Documents/downloaded_video.mp4
2013-07-24 00:13:32.374 App[1716:907] Wrote image with metadata to Photo Library (null)

And of course the file is not saved in the camera roll. It's a simple mp4, compatible with the device I'm using (i.e. it should be possible to save it).

I honestly have no idea what to do. Any hint will be highly appreciated. Thanks

Upvotes: 3

Views: 7597

Answers (3)

Ryan
Ryan

Reputation: 490

Here's a shorter answer.

In my case, I've used AFNetworking to download a video from a URL and in the downloadCompletedBlock of the download operation, responseObject returns the download file. Logging responseObject returns me the full file path of the downloaded video.

If you are using another method to download videos, simply replace responseObject with the full file path of your video, probably with the usual NSSearchPathForDirectoriesInDomains method.

Here's the snippet I use to export videos in the application's local file directory to the Camera Roll:

NSURL *responseObjectPath = [NSURL URLWithString:responseObject];
// If video is compatible with Camera Roll
if ([[ALAssetsLibrary new] videoAtPathIsCompatibleWithSavedPhotosAlbum:responseObjectPath])
{
    // Export to Camera Roll
    [[ALAssetsLibrary new] writeVideoAtPathToSavedPhotosAlbum:responseObjectPath completionBlock:nil];
}
else
{
    NSLog(@"Incompatible File Type");
}

Cheers!

Upvotes: 0

Josh Buhler
Josh Buhler

Reputation: 27678

I may have found a workaround for you. Have you tried an AVAssetExportSession?

In the sample below, I built a simple app that has two buttons on the screen. One calls onSaveBtn:, which simply grabs the URL of a video I have in my app's resource bundle and saves it to the user's saved photos album. (Though, in my case my videos do return YES from videoAtPathIsCompatibleWithSavedPhotosAlbum:. I didn't have any videos that don't return otherwise.)

The second button is wired to onExportBtn:, which takes the video we want to save, creates an AVAssetExportSession, exports the video to a temp directory, and then copies the exported video to the saved photos album. Due to the export time, this method does take longer than a simple copy, but maybe this could be an alternate path - check the results of videoAtPathIsCompatibleWithSavedPhotosAlbum:, and if YES, copy directly to the album. Otherwise, export the video, then copy.

Without having a video file that doesn't return NO to the compatibility call, I'm not 100% sure this would work for you, but it's worth a shot.

You may also want to check out this question, which explores what video formats are compatible on the device you may be using.

#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>

- (IBAction)onSaveBtn:(id)sender
{
    NSURL *srcURL = [[NSBundle mainBundle] URLForResource:@"WP_20121214_001" withExtension:@"mp4"];
    [self saveToCameraRoll:srcURL];
}

- (IBAction)onExportBtn:(id)sender
{
    NSURL *srcURL = [[NSBundle mainBundle] URLForResource:@"WP_20121214_001" withExtension:@"mp4"];
    AVAsset *srcAsset = [AVAsset assetWithURL:srcURL];

    // create an export session
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:srcAsset presetName:AVAssetExportPresetHighestQuality];

    // Export the file to a tmp dir
    NSString *fileName = [srcURL lastPathComponent];
    NSString *tmpDir = NSTemporaryDirectory();
    NSURL *tmpURL = [NSURL fileURLWithPath:[tmpDir stringByAppendingPathComponent:fileName]];

    exportSession.outputURL = tmpURL;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;

    [exportSession exportAsynchronouslyWithCompletionHandler:^{       
        // now copy the tmp file to the camera roll
        switch ([exportSession status]) {
            case AVAssetExportSessionStatusFailed:
                NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"Export canceled");
                break;
            case AVAssetExportSessionStatusCompleted:
                NSLog(@"Export successful");
                [self saveToCameraRoll:exportSession.outputURL];
                break;
            default:
                break;
        }
    }];
}

- (void) saveToCameraRoll:(NSURL *)srcURL
{
    NSLog(@"srcURL: %@", srcURL);

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    ALAssetsLibraryWriteVideoCompletionBlock videoWriteCompletionBlock =
    ^(NSURL *newURL, NSError *error) {
        if (error) {
            NSLog( @"Error writing image with metadata to Photo Library: %@", error );
        } else {
            NSLog( @"Wrote image with metadata to Photo Library %@", newURL.absoluteString);
        }
    };

    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:srcURL])
    {
        [library writeVideoAtPathToSavedPhotosAlbum:srcURL
                                    completionBlock:videoWriteCompletionBlock];
    }
}

Upvotes: 9

Sabby
Sabby

Reputation: 2592

Where are you providing the URL to the block. I think you need to do this way..

NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:^(NSURL *assetURL, NSError *error){
       /*notify of completion*/
       NSLog(@"AssetURL: %@",assetURL);
       NSLog(@"Error: %@",error);
       if (!error) {
            //video saved

       }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:error.domain delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                [alert release];
       }

}];

You can change the url here, I have used for the imagePickerController.. See if its helps you..

Upvotes: 0

Related Questions