【发布时间】:2017-07-01 19:06:58
【问题描述】:
好的,我已经成功下载了各种 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?
【问题讨论】:
-
嘿!你有没有找到任何解决方案?我有同样的错误。
-
有什么解决办法吗?
-
我很难复制这个,是否可以在 github 上附加一个工作示例?
标签: ios swift nsurlsession nsurlsessiondownloadtask