Download in documents directory or move file async - iOS

后端 未结 2 1910
醉酒成梦
醉酒成梦 2021-02-07 12:32

I am building an iOS app in which the user can download different files.
I am using an URLSessionDownloadTask and an URLSession to download a file

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 12:57

    Amusingly, the correct answer to this was posted in another question, where it was not the correct answer.

    The solution is covered in Apple's Documentation where they state:

    location

    A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method.

    If you choose to open the file for reading, you should do the actual reading in another thread to avoid blocking the delegate queue.

    You are probably calling simpleMove from the success handler for the DownloadTask. When you call simpleMove on a background thread, the success handler returns and your temp file is cleaned up before simpleMove is even called.

    The solution is to do as Apple says and open the file for reading:

    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        do {
            let file: FileHandle = try FileHandle(forReadingFrom: location)
            
            DispatchQueue.global().async {
                let data = file.readDataToEndOfFile()
                FileManager().createFile(atPath: destination, contents: data, attributes: nil)
            }
        } catch {
            // Handle error
        }
    }
    

提交回复
热议问题