如何将video片段保存到照片库 – ios 8&9

我已经努力将video剪辑保存到照片库。 这里的代码如下,但它不工作。 即使saveVideo返回true,但我打开照片库无法获取video剪辑。

文件path

是本地文档目录上的位置

func saveVideo(filePath: String) { UISaveVideoAtPathToSavedPhotosAlbum (filePath, self,"video:didFinishSavingWithError:contextInfo:", nil) } func video(filePath: String, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) { if error == nil { let ac = UIAlertController(title: "Saved!", message: "Your altered video has been saved to your gallery.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } else { let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } } 

尝试使用此类别来存储和更新PHAsset(图像/video),

https://github.com/zakkhoyt/PHAsset-Utility

在这个库中,您必须提供PHAsset对象到块的类别操作。

试试这个:

对于Objective – C.

此代码用于从互联网下载video并将其保存到照片库。

 NSURL *videoUrl = [NSURL URLWithString:[NSString stringWithFormat:@"Your Video Url"]]; dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(q, ^{ NSData *videoData = [NSData dataWithContentsOfURL:videoUrl]; dispatch_async(dispatch_get_main_queue(), ^{ // Write it to cache directory NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.mov"]; [videoData writeToFile:videoPath atomically:YES]; // After that use this path to save it to PhotoLibrary ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath] completionBlock:^(NSURL *assetURL, NSError *error) { if (error) { NSLog("Error"); } else { NSLog("Success"); } }]; }); }); 

您可以在开发适用于iOS 9.0或更高版本的应用程序时使用PHPhotoLibrary代替ALAssetsLibrary

你可以通过转换成swift语法在Swift中使用上面的代码。

 PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in let createAssetRequest: PHAssetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(NSURL(string: filePath)!)! createAssetRequest.placeholderForCreatedAsset }) { (success, error) -> Void in if success { //popup alert success } else { //popup alert unsuccess } }