Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 851
blue Avatar asked Jul 01 '17 19:07

blue


1 Answers

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
like image 157
Graham Perks Avatar answered Oct 05 '22 23:10

Graham Perks