title: Download in documents directory or move file async - iOS
body: <p>I am building an iOS app in which the user can download different files.<br>
  I am using an <code>URLSessionDownloadTask</code> and an <code>URLSession</code> to download a file asynchronously.<br>When the download is finished, the destination folder is by default, the <code>tmp/</code> directory.<br>
  So, when the download ends, I need to move the temporary file to another directory.<br>For a picture or a song, this takes only 1 second maybe even less.<br> But when the file is a video for example, it can take up to 15 seconds.<br></p>
  
  <h1>The issue</h1>
  
  <p>To allow the user to still interact with the app, I would like to make this move asynchronous.<br>Each time I try to do that, the file manager throws an exception.<br></p>
  
  <blockquote>
    <p>“CFNetworkDownload_xxxxxx.tmp” couldn’t be moved to “Downloads” because either the former doesn't exist, or the folder containing the latter doesn't exist.</p>
  </blockquote>
  
  <h3>What have I tried</h3>
  
  <p>I tried to put the call to the file manager in a background thread, it throws.</p>
  
  <p>I tried to remove the destination file before calling the move method, to make sure that the file doesn't already exists.</p>
  
  <p>I tried to make a call to the <code>copy</code> function, before removing the file from the <code>tmp/</code> directory.</p>
  
  <h3>My code</h3>
  
  <p>The call to the file manager looks like that.</p>
  
  <pre><code>func simpleMove(from location: URL, to dest: URL) -&gt; Bool {
      let fileManager = FileManager.default
      do {
          try fileManager.moveItem(at: location, to: dest)
          return true
      } catch {
          print("\(error.localizedDescription)")
          return false
      }
  }
  </code></pre>
  
  <p>When I put that in a background thread, I do it like that.</p>
  
  <pre><code>DispatchQueue.global().async {
      if !simpleMove(from: location, to: dest) {
          //Failure
      }
  }
  </code></pre>
  
  <h1>Questions</h1>
  
  <p>How can I possibly move a really large file without affecting the UI?</p>
  
  <p>It would be an even better solution to download the file directly in a permanent directory. How can I do that?</p>
  
  <p>When I make the call to my <code>simpleMove(from:to:)</code> synchronously, it works perfectly.<br>So, why the error says that the destination directory doesn't exists? (or something like that, I'm not sure of the meaning of that error)</p>
  
  <p>Thanks.</p>
  
  <h3>Note</h3>
  
  <p>The code above is written in Swift 3, but if you have an Objective-C or a Swift 2 answer,<br>feel free to share it as well!</p>