4

I'm starting with just an NSString that is a url to an .mp4 file, and from here I would like to have that video saved to the device camera roll. It seems I can only save .mov files, so I have to first convert the .mp4, but the few posts I've seen about this didn't help.

Can anyone help me accomplish this?

Thanks in advance...

SeanT
  • 1,741
  • 1
  • 16
  • 24

1 Answers1

12

You can save an mp4 file to the camera roll provided it uses supported codecs. For example:

NSURL *sourceURL = [NSURL URLWithString:@"http://path/to/video.mp4"];

NSURLSessionTask *download = [[NSURLSession sharedSession] downloadTaskWithURL:sourceURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL *tempURL = [documentsURL URLByAppendingPathComponent:[sourceURL lastPathComponent]];
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:tempURL error:nil];
    UISaveVideoAtPathToSavedPhotosAlbum(tempURL.path, nil, NULL, NULL);
}];

[download resume];

Or, on iOS 6 and above:

NSURL *sourceURL = [NSURL URLWithString:@"http://path/to/video.mp4"];
NSURLRequest *request = [NSURLRequest requestWithURL:sourceURL];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL *tempURL = [documentsURL URLByAppendingPathComponent:[sourceURL lastPathComponent]];
    [data writeToURL:tempURL atomically:YES];
    UISaveVideoAtPathToSavedPhotosAlbum(tempURL.path, nil, NULL, NULL);
}];
jonahb
  • 2,570
  • 16
  • 22
  • Thank you very much for your input, your solution seems to work perfectly in iOS 7, but I need to make it work in iOS 6.1+. Any ideas? – SeanT Jan 14 '14 at 21:21
  • You'll have to download the file with `NSURLConnection` or a third party library. You'll still want to write it to a temp file and then call `UISaveVideoAtPathToSavedPhotosAlbum`. – jonahb Jan 14 '14 at 21:31
  • @SeanT, I added an iOS 6 example. – jonahb Jan 15 '14 at 01:17
  • @jonahb Could you offer some advice on my [SO Question](http://stackoverflow.com/questions/31965566/how-to-efficiently-write-large-files-to-disk-on-background-thread-swift) for handling large amounts of data. I'm interested in ensuring that saving data to a video file is handled correctly on a background thread. It almost appears that your solution might work but the implications of threading are not apparent. Thanks for your thoughts in advance. – Tommie C. Aug 14 '15 at 12:07