Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 460
Ankit Kumar Gupta Avatar asked Apr 25 '17 10:04

Ankit Kumar Gupta


4 Answers

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.
                    })
            }
}
like image 158
Ankit Kumar Gupta Avatar answered Nov 16 '22 14:11

Ankit Kumar Gupta


First, you need to set the following permission in your app's plist file:

Privacy - Photo Library Usage Description

Provide a string that is presented to the user explaining why you are requesting the permission.

Next,

import photos

Then use this code to store video

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

To get url from PHAsset, refer to this question's answer

like image 43
Surjeet Singh Avatar answered Nov 16 '22 13:11

Surjeet Singh


If you want to fetch the saved element (not using a sort descriptor with date order), you can do it this way:

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
                } 
            }
}
like image 3
Bisca Avatar answered Nov 16 '22 13:11

Bisca


Try like this!

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)
            })
      }
}
like image 1
Bhupat Bheda Avatar answered Nov 16 '22 13:11

Bhupat Bheda