如何将视频剪辑保存到照片库 - ios 8 & 9

How to save video clip to Photos gallery - ios 8 & 9

我想办法将视频剪辑保存到照片库。 这里的代码如下,但它不起作用。 虽然saveVideoreturn是真的,但是我打开Photos gallery无法获取视频片段。

filepath

是本地文档目录中的位置

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

试试这个:-

对于Objective - C.

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

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 中使用上述代码。

尝试使用此类别来存储和更新 PHAsset (Image/Video),

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

在此库中,您必须将 PHAsset 对象提供到块中以进行类别操作。

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
            }
    }