将MP4视频保存到设备相册

4
我从一个NSString开始,它是指向一个.mp4文件的url。我想将该视频保存到设备相机胶卷中。似乎我只能保存.mov文件,因此我必须先转换.mp4文件,但我看到的几篇文章都没有帮助。
有人能帮我完成这个任务吗?
提前感谢...
1个回答

12

只要使用支持的编解码器,可以将mp4文件保存到相机胶卷中。例如:

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];

或者,在iOS 6及以上版本:

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);
}];

非常感谢您的输入,您的解决方案似乎在iOS 7上完美运行,但我需要让它在iOS 6.1+上运行。有什么想法吗? - SeanT
你需要使用NSURLConnection或第三方库下载文件。你仍然需要将其写入临时文件,然后调用UISaveVideoAtPathToSavedPhotosAlbum - jonahb
@SeanT,我添加了一个iOS 6的示例。 - jonahb
@jonahb,你能就我的SO问题提供一些建议吗?我想确保在后台线程上正确处理将数据保存到视频文件中。你的解决方案似乎可以工作,但线程的影响并不明显。提前感谢你的想法。 - Tommie C.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接