Search code examples
iosswiftvideouiimagepickercontrollerphotokit

Save video to the gallery and get the path for the video stored to Gallery


I want to save a video chosen from UIImagePickerController to the Photos album. After that i need to fetch the URL to the saved path. I saw some pre-existing questions which answer with use of ALAssetsLibrary which is now deprecated. Like : Save video on the gallery and store the path to the video

Can someone please guide me to use Photo's framework and achieve the above desired result. Kindly correct me if I am wrong anywhere.

Thanks!!


Solution

  • This worked for me perfectly.

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