Save the video in the gallery and find the path to the video saved in the gallery

I want to save the video selected from UIImagePickerControllerto the Photos album. After that, I need to get the URL of the saved path. I saw some pre-existing questions that are answered using a ALAssetsLibrarythat is now deprecated. For example: Save video in gallery and save video path

Maybe someone will ask me to use Photo frameworkand achieve the above desired result. Please correct me if I'm wrong somewhere.

Thanks!!

+5
source share
6 answers

.

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.
                    })
            }
}
+15

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

URL- PHAsset,

+7

( ), :

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

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

import AVKit AVPlayerViewController

Import Photos and PhotosUI to save videos using PHAsset.

Hope this helps!

+1
source

Try it!

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)
            })
      }
}
+1
source

Here is the answer to Objective-C

Code example:

 [[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 the url to the file
                                              NSURL *url = (NSURL *)[(AVURLAsset *)asset URL];


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

Hope this helps Thanks

+1
source

Source: https://habr.com/ru/post/1016750/


All Articles