gpt4 book ai didi

ios - Swift:URLSessionDownload 文件说它存在但实际上不存在?

转载 作者:IT王子 更新时间:2023-10-29 05:31:54 25 4
gpt4 key购买 nike

好的,我已经成功下载了各种 m4a 文件并通过 URLSession 删除了它们。我的问题是 URLSessionDownloadDelegate 要求的最终“完成”功能,有时我会在控制台打印以下内容,即使我检查我的下载功能(在下载之前)文件是否存在于目录中。很困惑。这是消息:

File download succesfully
“CFNetworkDownload_1wGgxs.tmp” couldn’t be moved to “Documents” because an item with the same name already exists.
The task finished successfully

这是下载功能,我在其中明确检查文件是否存在:

func goDownload()
{
if let audioUrl = downloadUrl { //set at beginning

let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print(destinationUrl)

// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("********** The file already exists at path")

// if the file doesn't exist
} else {

print("---------------> Starting Download")


currentTask = session.downloadTask(with: audioUrl)
currentTask.resume()
}
}
}

这是完成函数:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

print("File download succesfully")
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent((downloadUrl?.lastPathComponent)!)

do {
try FileManager.default.moveItem(at: location, to: destinationUrl)

//success
print("************** SUCCESS File moved to documents folder", downloadUrl)
playModeStreaming = false

self.pausePlay()
AudioPlayerManager.shared.play(url: downloadUrl)

} catch let error as NSError {
print(error.localizedDescription)
}


}

我什至实现了一个检查函数,它返回文件是否存在,在收到上述消息后,它返回 false:

func checkIfExists(url: URL)->Bool
{
return FileManager.default.fileExists(atPath: url.path)
}

这是什么原因造成的?我怎样才能确保它下载以便它可以播放 m4a?

最佳答案

您的代码非常接近 Apple's sample code在标题为“处理下载完成和错误”的部分中。但不完全是……您的 print("File download successfully") 做出了很大的假设!

我在 urlSession:... didFinishDownloadingTo: 中看到的差异是您跳过了 downloadTask.response.statusCode 的检查以确保下载成功。 Apple 检查它在 200...299 范围内。

您可以尝试添加此 HTTP 状态代码检查,以防您收到的错误消息是虚假的并且您实际上遇到了网络故障。

苹果网站的校验码:

...
didFinishDownloadingTo location: URL) {

guard let httpResponse = downloadTask.response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print ("server error")
return
}

... now do the FileManager code

关于ios - Swift:URLSessionDownload 文件说它存在但实际上不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com