Swift:URLSessionDownload file says it exists but it doesn't?
Asked Answered
L

1

13

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?

Litalitany answered 1/7, 2017 at 19:6 Comment(3)
Hey! Did you find any solution for this ? I am having same error.Milena
any solutions to this?Emendate
I am having a hard time reproducing this, is it possible to attach a working example on github?Smearcase
V
5

Your code is very close to Apple's sample code in the section titled "Handle Download Completion and Errors". But not quite... your print("File download succesfully") is making a big assumption!

The delta I see in urlSession:... didFinishDownloadingTo: is that you're skipping the check of downloadTask.response.statusCode to ensure the download was successful. Apple checks it's in the range 200...299.

You might try adding this HTTP status code check, in case the error message you're getting is bogus and you're actually experiencing network failures.

The checking code from Apple's site:

...
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
Volt answered 22/11, 2018 at 14:44 Comment(1)
For me, the status code is 200 here, but the file cannot be found by doing the following: try FileManager.default.copyItem(atPath: location.absoluteString, toPath: ...)Surtout

© 2022 - 2024 — McMap. All rights reserved.