I am creating an iOS application in which a user can upload different files.
I use URLSessionDownloadTask and URLSession to download the file asynchronously.
When the download is finished, the default destination folder is the tmp/ .
So, when the download finishes, I need to move the temporary file to another directory.
For an image or song, it only takes 1 second, perhaps even less.
But when the file is a video, for example, it can take up to 15 seconds.
Problem
To allow the user to still interact with the application, I would like to make this step asynchronous.
Every time I try to do this, the file manager throws an exception.
CFNetworkDownload_xxxxxx.tmp cannot be moved to Downloads because either the former does not exist or the folder containing the latter does not exist.
What i tried
I tried to put a call to the file manager in the background thread, it throws.
I tried to delete the destination file before calling the move method to make sure the file does not exist yet.
I tried calling the copy function before deleting the file from the tmp/ .
My code
A file manager call looks like this.
func simpleMove(from location: URL, to dest: URL) -> Bool { let fileManager = FileManager.default do { try fileManager.moveItem(at: location, to: dest) return true } catch { print("\(error.localizedDescription)") return false } }
When I put this in the background thread, I do it like this.
DispatchQueue.global().async { if !simpleMove(from: location, to: dest) {
Questions
How can I move a really large file without affecting the user interface?
This would be an even better solution to upload the file directly to the permalink. How can i do this?
When I make a call for my simpleMove(from:to:) synchronously, it works fine.
So, why does the error indicate that the target directory does not exist? (or something like that, I'm not sure about the meaning of this error)
Thanks.
Note
The above code is written in Swift 3, but if you have an Objective-C or Swift 2 answer, feel free to share it as well!