How to download a video using a URL and save it in an photo album using Swift?

SwiftiOSiPhone/iPadMobile Development

To download a video from a URL in swift we need to perform a few steps while keeping a few things in mind.

Points to be noted here are,

  • We’ll be making use of internet to download video, hence we need to allow permissions for App transport security in our Info.plist

  • We’ll need to save the downloaded video to Photos app, hence photos permission is required.

  • Video should always be downloaded in background as it may prevent us from using the app if downloaded on foreground.

Now, we’ll use the below code to save a video from a random link in our Device. You’ll need to allow photos permission while running the app.

Now first add the following code to your info.plist file.

<key>NSPhotoLibraryUsageDescription</key>
<string>saves</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

After this, now add the function shown below and call it inside the viewDidLoad method of your class.

Now your viewDidLoad should look like −

override func viewDidLoad() {
   super.viewDidLoad()
   self.downloadVideo()
}

Below is the code for function to download a video.

func downloadVideo() {
   let sampleURL = "http://commondatastorage.googleapis.com/gtv-videosbucket/sample/ElephantsDream.mp4"DispatchQueue.global(qos: .background).async {
      if let url = URL(string: sampleURL), let urlData = NSData(contentsOf: url) {
         let galleryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
         let filePath="\(galleryPath)/nameX.mp4" DispatchQueue.main.async {
            urlData.write(toFile: filePath, atomically: true)
               PHPhotoLibrary.shared().performChanges({
               PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL:
               URL(fileURLWithPath: filePath))
            }) {
               success, error in
               if success {
                  print("Succesfully Saved")
               } else {
                  print(error?.localizedDescription)
               }
            }
         }
      }
   }
}

As there is no other UI element on the screen do not expect to see any result on the screen, only the print statements will be shown in output and if successfully done, the video will be saved to photos which can be seen in the Photos app.

raja
Updated on 29-Jun-2020 14:07:25

Advertisements