如何使用URL下载视频并使用Swift将其保存在相册中?

要快速从URL下载视频,我们需要执行一些步骤,同时牢记一些注意事项。

这里要注意的要点是,

  • 我们将利用互联网下载视频,因此我们需要在Info.plist中允许App传输安全性权限

  • 我们需要将下载的视频保存到“照片”应用中,因此需要照片权限。

  • 视频应始终在后台下载,因为如果在前台下载,则可能会阻止我们使用该应用。

现在,我们将使用以下代码将来自随机链接的视频保存到我们的设备中。在运行应用程序时,您需要允许照片权限。

现在,首先将以下代码添加到您的info.plist文件中。

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

之后,现在添加如下所示的函数,并在您的类的viewDidLoad方法内调用它。

现在您的viewDidLoad应该看起来像-

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

以下是下载视频的功能代码。

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

由于屏幕上没有其他UI元素,因此预期不会在屏幕上看到任何结果,因此仅打印语句将显示在输出中,如果成功完成,则视频将保存到可以在“照片”应用程序中查看的照片。