Download in documents directory or move file async - iOS

后端 未结 2 1911
醉酒成梦
醉酒成梦 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:46

    I came across the same issue but i solve it.

    First check that the file is exist in that path because i got issue because of the path extension are different of location URL. i was trying to rename audio but path extension was different(eg. mp3 to m4a)

    Also in case there is any other file already exists at destination path this issue arise.

    So first try to check file exists at location where you by using

     let fileManager = FileManager.default
    
     if fileManager.fileExists(atPath: location.path) {
         do {
             try fileManager.moveItem(at: location, to: dest)
             return true
         } catch {
             print("\(error.localizedDescription)")
             return false
         }
     }
    

    Hope this will help you

    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
提交回复
热议问题