Swift: URLSessionDownload file says it exists, but it doesn't?
Ok, I was able to download various m4a files as well as delete them via URLSession. My problem is the final "completed" function of the URLSessionDownloadDelegate requirement, sometimes I get the following printout to the console even if I check the download (before downloading) whether the file exists in the directory or not. Very confused. Here is the message:
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
This is where the func is loaded where I CHECK YOUR WEEK if the file exists:
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()
}
}
}
Here's where the completion function runs:
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)
}
}
I even implemented a check function that returns if a file exists or not, and after receiving the above message, it returns false:
func checkIfExists(url: URL)->Bool
{
return FileManager.default.fileExists(atPath: url.path)
}
What is causing this? How can I make sure it loads so that it can play m4a?
source to share
No one has answered this question yet
Check out similar questions: