将视频保存到图库并获取存储到图库

时间:2017-04-25 10:40:18

标签: ios swift video uiimagepickercontroller photokit

我想将从UIImagePickerController中选择的视频保存到相册。 之后我需要获取保存路径的URL。我看到了一些预先存在的问题,这些问题通过使用现已弃用的ALAssetsLibrary来回答。 喜欢:Save video on the gallery and store the path to the video

有人可以指导我使用Photo's framework并达到上述预期效果。如果我在任何地方都错了,请纠正我。

谢谢!

6 个答案:

答案 0 :(得分:13)

这对我很有用。

Swift 3.1 - >

PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url!)
}) { saved, error in
            if saved {
                let fetchOptions = PHFetchOptions()
                fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

                // After uploading we fetch the PHAsset for most recent video and then get its current location url

                let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).lastObject 
                PHImageManager().requestAVAsset(forVideo: fetchResult!, options: nil, resultHandler: { (avurlAsset, audioMix, dict) in
                    let newObj = avurlAsset as! AVURLAsset
                    print(newObj.url) 
                    // This is the URL we need now to access the video from gallery directly.
                    })
            }
}

答案 1 :(得分:5)

首先,您需要在应用的plist文件中设置以下权限:

隐私 - 照片库使用说明

提供一个字符串,呈现给用户,解释您申请许可的原因。

接下来,

import photos

然后使用此代码存储视频

    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL)
    }) { saved, error in
        if saved {
            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

            let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).firstObject
            // fetchResult is your latest video PHAsset
            // To fetch latest image  replace .video with .image
        }
    }

要从PHAsset获取网址,请参阅此question's answer

答案 2 :(得分:2)

如果要获取已保存的元素(不使用带日期顺序的排序描述符),可以这样做:

var changeRequest: PHAssetChangeRequest?
var blockPlaceholder: PHObjectPlaceholder?

PHPhotoLibrary.shared().performChanges({
            changeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url!)
            blockPlaceholder = changeRequest?.placeholderForCreatedAsset
}) { saved, error in
            if saved {
                guard let placeholder = blockPlaceholder else {
                    return
                }
                let fetchOptions = PHFetchOptions()
                let fetchResult:PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: fetchOptions)
                if let asset = fetchResult.firstObject {
                    //here you have the PHAsset
                } 
            }
}

答案 3 :(得分:1)

我是通过创建URL类的扩展

来实现的
extension URL {

    func saveVideo( success:@escaping (Bool,URL?)->()){


        URLSession.shared.downloadTask(with: URLRequest(url: self)) { (url, response, error) in

            let mgr = FileManager.default

            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]


            let destination = URL(fileURLWithPath: String(format: "%@/%@", documentsPath, "video.mp4"))


            try? mgr.moveItem(atPath: /url?.path, toPath: /destination.path)

            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destination)
            }) { completed, error in
                if completed {
                    print("Video is saved!")
                    success(true,destination)
                }
                if error != nil{
                    success(false,nil)
                }
            }
        }.resume()
    }
}

当您想要保存并播放时,您可以在ViewController中将其用作

guard let urlToDownload = URL(string: videoURLStringToDownload) else { return }

  urlToDownload.saveVideo(success: { (isSaved,url) in           
    guard let videoURL = url, isSaved else { return }

        let player = AVPlayer(url: videoURL)
          let playerViewController = AVPlayerViewController()
           playerViewController.player = player
          self.present(playerViewController, animated: true) {
                            playerViewController.player?.play()
          }
    })

导入 AVKit ,通过AVPlayerViewController播放视频

导入照片 PhotosUI ,以便使用PHAsset保存视频。

希望它有所帮助!

答案 4 :(得分:1)

试试这个!

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
if mediaType.isEqualToString(kUTTypeMovie as NSString as String) || mediaType.isEqualToString(kUTTypeVideo as NSString as String){
    let videoPath = info[UIImagePickerControllerMediaURL] as! NSURL // Path of video Url
    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
    let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoPath)
    let assetPlaceholder = createAssetRequest?.placeholderForCreatedAsset
    let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset)
            albumChangeRequest!.addAssets([assetPlaceholder!])
       }, completionHandler: { (success, error) in
                    NSLog("Adding video to Library ->%@", (success ? "Success" : "Error"))
                    picker.dismissViewControllerAnimated(true, completion: nil)
            })
      }
}

答案 5 :(得分:0)

这是Objective-C的答案

代码示例:

 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
    [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL URLWithString:urlOfFile]];
} completionHandler:^(BOOL success, NSError *error) {
                                      if (success)
                                      {
                                          PHFetchOptions *fetchOptions = [[PHFetchOptions alloc]init];
                                          fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:false]];
                                          PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:fetchOptions];
                                          PHAsset *lastAsset = [fetchResult lastObject];
                                          [[PHImageManager defaultManager] requestAVAssetForVideo:lastAsset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
                                              //here's the url to the file
                                              NSURL *url = (NSURL *)[(AVURLAsset *)asset URL];


                                      }else{
                                          NSLog(@"%@",error.description);
                                      }
                                  }];

希望有帮助 谢谢