Swift:URLSessionDownload文件说它存在,但它不存在?

时间:2017-07-01 19:06:59

标签: ios swift nsurlsession nsurlsessiondownloadtask

好的,我已成功下载各种m4a文件,并通过URLSession删除它们。我的问题是在URLSessionDownloadDelegate要求的最终“完成”功能中,我有时会将以下内容打印到控制台,即使我检查下载功能(下载前)是否该文件存在于目录中。非常困惑。这是消息:

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

这是下载功能,我在其中检查是否存在文件:

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()
            }
        }
    }

这是完成功能:

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)
        }


    }

我甚至实现了一个check func,它返回文件是否存在,在获得上述消息后,它返回false:

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

造成这种情况的原因是什么?如何确保下载以便它可以播放m4a?

1 个答案:

答案 0 :(得分:3)

您的代码与标题为“处理下载完成和错误”的部分中的Apple's sample code非常接近。但是还不完全是……您的print("File download succesfully")做出了很大的假设!

我在urlSession:... didFinishDownloadingTo:中看到的差异是,您跳过了downloadTask.response.statusCode的检查以确保下载成功。苹果检查它的范围是200 ... 299。

如果您收到的错误消息是虚假的,并且您实际上遇到网络故障,则可以尝试添加此HTTP状态代码检查。

Apple网站上的检查代码:

...
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