Ok, I have succeeded in downloading various m4a files as well as removing them via URLSession. My problem is in the final "completion" function of the URLSessionDownloadDelegate requirement, I sometimes get the following printed to console even though I check in my download func( before downloading) whether the file exists in the directory or not. Very confused. Here is 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
Here is download func where I CHECK EXPLICITLY whether 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 is completion func:
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 have even implemented a checking func that returns whether the file exists or not and after getting 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 downloads so that it can play the m4a?