title: how to save file in background thread using Swift?
body: <p>I'm trying to make an application that uses a web service to get some data from a directory, but I also need to save the data into the device, include images, to do so I'm using <strong>Alamofire</strong> and <strong>AlamofireImage</strong> framework for consuming the webservice. I save the generated objects in a database with <strong>Realm</strong> framework and for images I save the <strong>UIImage</strong> into a file. </p>
  
  <p>Basically, the ViewController has a tableView which displays de data, but it seems laggy because of the images writing into files.</p>
  
  <p>This is my writing function:</p>
  
  <pre><code>func saveImage(_ image: UIImage) {
      if let data = UIImagePNGRepresentation(image) {
          let name = "images/person_directory_\(id).png"
          let docsDir = getDocumentsDirectory()
          let filename = docsDir.appendingPathComponent(name)
          let fm = FileManager.default
  
          if !fm.fileExists(atPath: docsDir.appendingPathComponent("images").path) {
              do {
                  try fm.createDirectory(at: docsDir.appendingPathComponent("images"), withIntermediateDirectories: true, attributes: nil)
                  try data.write(to: filename)
                  try! realm?.write {
                      self.imageLocal = name
                  }
              }
              catch {
                  print(error)
              }
          }
          else {
              do {
                  try data.write(to: filename, options: .atomic)
                  try! realm?.write {
                      self.imageLocal = name
                  }
              }
              catch {
                  print(error)
              }
  
          }
      }
  }
  </code></pre>
  
  <p>I call this function when <strong>Alamofire</strong> downloads the image</p>
  
  <pre><code>if person.imageLocal != nil,  let image = person.loadLocalImage() {
          print("Load form disk: \(person.imageLocal)")
          cell.imgProfile.image = image
      }
      else if !(person.image?.isEmpty)! {
          Alamofire.request(person.image!).responseImage(completionHandler: { (response) in
              if response.result.isSuccess {
                  if let image = response.result.value {
                      person.saveImage(image)
                      cell.imgProfile.image = image
                      print("Downloaded: \(person.imageLocal)")
                  }
              }
          })
      }
  </code></pre>
  
  <p>But the tableView looks laggy when scrolled and I was trying to make the writing operation into a diferent thread so it could get written without affecting the application performance by using <strong>DispatchQeue</strong></p>
  
  <pre><code>DispatchQueue.global(qos: .background).async {
                      do {
                          try data.write(to: filename)
                      }
                      catch {
                          print(error)
                      }
                  }
  </code></pre>
  
  <p>But even so the applications stills laggy.</p>
  
  <p>UPDATE:</p>
  
  <p>I tryed this as Rob suggested:</p>
  
  <pre><code>func saveImage(_ image: UIImage) {
      if let data = UIImagePNGRepresentation(image) {
          let name = "images/person_directory_\(id).png"
          do {
              try realm?.write {
                  self.imageLocal = name
              }
          }
          catch {
              print("Realm error")
          }
          DispatchQueue.global().async {
              let docsDir = self.getDocumentsDirectory()
              let filename = docsDir.appendingPathComponent(name)
              let fm = FileManager.default
  
              if !fm.fileExists(atPath: docsDir.appendingPathComponent("images").path) {
                  do {
                      try fm.createDirectory(at: docsDir.appendingPathComponent("images"), withIntermediateDirectories: true, attributes: nil)
                  }
                  catch {
                      print(error)
                  }
              }
              do {
                  try data.write(to: filename)
              }
              catch {
                  print(error)
              }
          }
      }
  }
  </code></pre>
  
  <p>I can't dispatch the Realm writing becase Realm doesn't suport multithreading.
  It stills scrolling laggy but not as much as the first time.</p>