简体   繁体   English

使用Swift将视频文件保存到照片库

[英]Saving video file to photo gallery using Swift

I am coping one video of 20 seconds. 我正在处理一部20秒的视频。 I am facing to save that video on my photo gallery. 我正要将该视频保存到我的照片库中。 After successfully video trimming I need to call this function can any one help me to convert below code in Swift. 视频修剪成功后,我需要调用此函数,任何人都可以帮助我在Swift中转换以下代码。 I have pasted both version of code, if any one can identify my mistake? 我粘贴了两个版本的代码,是否有人可以识别我的错误?

Objective C 目标C

-(void)writeVideoToPhotoLibrary:(NSURL*)aURL
{
    NSURL *url = aURL;
    NSData *data = [NSData dataWithContentsOfURL:url];

    // Write it to cache directory
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.mov"];
    [data writeToFile:path atomically:YES];

    NSLog(@"Path:%@",path);

    // After that use this path to save it to PhotoLibrary

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:path] completionBlock:^(NSURL *assetURL, NSError *error) {

        if (error) {
            NSLog(@"%@", error.description);
        }else {
            NSLog(@"Done :)");
        }

    }];


}

Swift 迅速

 func SaveVideoToPhotoLibrary(outputFileURL: NSURL)

    {

        assetsLibrary = ALAssetsLibrary()

        let videoURL = outputFileURL as NSURL?

        if let library = assetsLibrary{

            if let url = videoURL{

                library.writeVideoAtPathToSavedPhotosAlbum(url,
                    completionBlock: {(url: NSURL!, error: NSError!) in

                        print(url)

                        if let theError = error{
                            print("Error happened while saving the video")
                            print("The error is = \(theError)")
                        } else {
                            print("no errors happened")
                        }

                })
            } else {
                print("Could not find the video in the app bundle")
            }

        }

            }
func saveToCameraRoll(URL: NSURL!) {
            NSLog("srcURL: %@", URL)
            var library: ALAssetsLibrary = ALAssetsLibrary()
            var videoWriteCompletionBlock: ALAssetsLibraryWriteVideoCompletionBlock = {(newURL: NSURL!, error: NSError!) in
                if (error != nil) {
            NSLog("Error writing image with metadata to Photo Library: %@", error)
        }
            else {
            NSLog("Wrote image with metadata to Photo Library %@", newURL.absoluteString!)
            }

            }
            if library.videoAtPathIsCompatibleWithSavedPhotosAlbum(URL) {
            library.writeVideoAtPathToSavedPhotosAlbum(URL, completionBlock: videoWriteCompletionBlock)
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM