如何使用 Swift 通过 URL 下载视频并将其保存到相册?

swiftiosiphone/ipadmobile development更新于 2026/2/19 23:52:17

要使用 Swift 通过 URL 下载视频,我们需要执行几个步骤,同时注意以下几点。

这里需要注意的几点是:

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

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

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

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

现在,首先将以下代码添加到您的 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 元素,所以不要期望在屏幕上看到任何结果,只有打印语句会显示在输出中,如果成功完成,视频将保存到照片中,可以在照片应用程序中看到。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部