Swift: save video from NSURL to user camera roll

George Poulos picture George Poulos · Apr 7, 2015 · Viewed 28.4k times · Source

I have a variable videoURL of type NSURL.

If I call println(videoURL) it would return something like this: http://files.parsetfss.com/d540f71f-video.mp4

I have a button set up that should take this videoURL and save the video to the user's camera roll.

The best I have done is this:

UISaveVideoAtPathToSavedPhotosAlbum(videoPath: String!, completionTarget: AnyObject!, completionSelector: Selector, contextInfo: UnsafeMutablePointer<Void>)

While I'm not even sure if this will work or not, I can't figure out how to convert videoFile:NSURL into a videoPath.

Any help is appreciated on this.

Edit:

The following is unsuccessful:

UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath, self, nil, nil)

Answer

Boris picture Boris · Jul 4, 2016

AssetsLibrary is deprecated

1: import Photos

import Photos

2: Use this code to save video from url to camera library.

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
             PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(nsUrlToYourVideo)
         }) { saved, error in
             if saved {
                 let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .Alert) 
                 let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
                 alertController.addAction(defaultAction)
                 self.presentViewController(alertController, animated: true, completion: nil)
             }
         }

Swift 3 & Swift 4

PHPhotoLibrary.shared().performChanges({
    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: urlToYourVideo)
}) { saved, error in
    if saved {
        let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(defaultAction)
        self.present(alertController, animated: true, completion: nil)
    }
}