urlSession download from remote url fail - CFNetworkDownload_gn6wzc.tmp appeared

自作多情 提交于 2020-12-15 04:56:40

问题


I was trying to download file from remote url using urlSession. But when the download is completed an unexpected file appeared named CFNetworkDownload_gn6wzc.tmpthen i cannot open that file using uidocumentinteractioncontroller. What is that file? how to fix this issue. Thank for reply.

Here is message

Your location is file:///Users/pisal/Library/Developer/CoreSimulator/Devices/26089E37-D4EA-49E5-8D45-BB7D9C52087D/data/Containers/Data/Application/767E966E-5954-41BA-B003-90E2D27C5558/Library/Caches/com.apple.nsurlsessiond/Downloads/com.SamboVisal.downloadTask/CFNetworkDownload_gn6wzc.tmp

Here is my sample code: i send link through this method

@IBAction func startDownload(_ sender: Any) {
    let url = URL(string: "http://www.tutorialspoint.com/swift/swift_tutorial.pdf")!
    let task = DownloadManager.shared.activate().downloadTask(with: url)
    task.resume()

}

Then when finished downloading:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        debugPrint("Download finished: \(location)")
        debugPrint("download task : \(downloadTask)")
        ViewController().documentInteraction(location: location)

    }

When i was trying to open uidocumentinteractioncontroller

let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
    let destinationPath = documentDirectoryPath.appendingPathComponent("swift.pdf")
    let destinationUrl = URL(fileURLWithPath: destinationPath)

    do{
        try FileManager.default.copyItem(at: locat, to: destinationUrl)
    }
    catch {
        print("error copying file: \(error.localizedDescription)")
    }

    documentInteractionController.url = destinationUrl

    if !documentInteractionController.presentOpenInMenu(from: openButton.bounds, in: view, animated: true) {
        print("You don't have an app installed that can handle pdf files.")
    }

回答1:


Downloaded data is stored in a temporary file. You need to write that data in your file and use that. Write following code in func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) method:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    debugPrint("Download finished: \(location)")
    do {
        let downloadedData = try Data(contentsOf: location)

        DispatchQueue.main.async(execute: {
            print("transfer completion OK!")

            let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
            let destinationPath = documentDirectoryPath.appendingPathComponent("swift.pdf")

            let pdfFileURL = URL(fileURLWithPath: destinationPath)
            FileManager.default.createFile(atPath: pdfFileURL.path,
                                           contents: downloadedData,
                                           attributes: nil)

            if FileManager.default.fileExists(atPath: pdfFileURL.path) {
                print("pdfFileURL present!") // Confirm that the file is here!
            }
        })
    } catch {
        print(error.localizedDescription)
    }
}

EDIT

When any file is downloaded from server, your app keeps all the data in temporary file. After downloading the file it gives you the URL where it temporary keeps your data. Now it's up to you how and where you want to store that data. Temporary files are not stored in Document directory. You need to copy the content of that file in your file with correct extension. Replace the given method in your code. When you want to read that file use swift.pdf not the tmp one.



来源:https://stackoverflow.com/questions/50383343/urlsession-download-from-remote-url-fail-cfnetworkdownload-gn6wzc-tmp-appeared

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!