قالب وردپرس درنا توس
Home / IOS Development / IOS – Swift: URLSessionDownload file says it exists, but it does not?

IOS – Swift: URLSessionDownload file says it exists, but it does not?



Ok, I managed to download different m4a files, as well as remove them via URLSession. My problem is in the final completion feature of the URLSessionDownloadDelegate requirement. Sometimes I get the following print to the console, even though I check my download function (before download) if the file is in the directory or not. Very confused. Here is the message:

  File download successful
"CFNetworkDownload_1wGgxs.tmp" could not be moved to "Documents" because an item with the same name already exists.
The task was completed

Here is the download function where I EXPLICITLY CHECK IF THE FILE IS:

  func goDownload ()
{
if let soundUrl = downloadUrl {// set in the beginning

la documentsDirectoryURL = FileManager.default.urls (for: .documentDirectory, in: .userDomainMask) .first!
la 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 on the path")

// if the file does not exist
} other {

print ("---------------> Start Download")


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

Here is the completion feature:

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

print ("File Download Successfully")
la documentsDirectoryURL = FileManager.default.urls (for: .documentDirectory, in: .userDomainMask) .first!

// lets us create your destination URL
la destinationUrl = documentsDirectoryURL.appendingPathComponent ((downloadUrl? .lastPathComponent)!)

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

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

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

} Capture Failed as NSError {
print (error.localizedDescription)
}


}

I've even implemented a control function that returns if the file exists or not, and after receiving the message above, it returns false:

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

What causes this? How can I make sure it is downloaded so that it can play m4a?


Source link