我想从远程网址下载并播放视频。首先,我使用 url 会话下载视频,下载后,将视频保存到文档目录,然后从文档目录播放视频。但是使用这种方法,我必须等到整个视频下载完成,然后才能将其保存到文档目录并播放。但我想要实现的是,我想将下载的视频部分连续保存到文档目录,以便我可以从文档目录连续播放它,而不必等到整个视频下载完成。那么有什么方法可以连续下载部分视频,以便将其保存到文档目录中。是否有任何 url 会话代表可以给我已经下载的部分或其他东西。
我使用 url 会话进行下载,并且 didFinishDownloadingTo 仅在下载完成后调用。下面是我到目前为止尝试过的代码。
public func downloadVideo(url: URL) {
let downloadTask = URLSession.shared.downloadTask(with: url) { (location, response, error) in
if let error = error {
print("Download error: \(error)")
return
}
guard let location = location else { return }
do {
let data = try Data(contentsOf: location)
print("downloaded data: \(data)")
} catch {
print("Error appending downloaded data: \(error)")
}
}
downloadTask.resume()
}}
extension MediaCacheManager: URLSessionDownloadDelegate {
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let data = try? Data(contentsOf: location) else {
return
}
guard let applicationSupportDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else {
print("Application Support directory not found")
return
}
// Create a subdirectory within Application Support, if needed
let subdirectoryURL = applicationSupportDirectory.appendingPathComponent("telehealthVideo")
do {
try FileManager.default.createDirectory(at: subdirectoryURL, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Error creating subdirectory: \(error.localizedDescription)")
return
}
let destinationURL = subdirectoryURL.appendingPathComponent("myVideo.mp4")
do {
print("destinationURL \(destinationURL)")
try data.write(to: destinationURL)
//saveVideoToAlbum(videoURL: destinationURL, albumName: "MyAlbum")
} catch {
print("Error saving file:", error)
}}
public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
DispatchQueue.main.async {
self.progress = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
debugPrint("progress \(self.progress)")
}
}}
只是为您指明正确的方向。您需要首先查看您的数据存储(后端)。通常,您不能只获取 URL 并下载文件大小的 10%,并期望它是视频的前 10%。