title: how can I modify my swift code so that it is being run in the background without blocking UI?
body: <p>I have a <code>UITableViewController</code> and on each cell I have a <code>UIImageView</code>. This image view is populated with a snapshot of a video stored on a server. As for now my code looks as follows:</p>
  
  <pre><code>func tableView(detailsPanel: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell {
      let cell = detailsPanel.dequeueReusableCellWithIdentifier("cell") as! DetailsCell
  
      let test:SingleTest =  self.items[indexPath.row] as! SingleTest
  
  //this code hangs up the UI for each cell:
      do {
          let asset = AVURLAsset(URL: NSURL(string: test.video)!, options: nil)
          let imgGenerator = AVAssetImageGenerator(asset: asset)
          imgGenerator.appliesPreferredTrackTransform = true
          let cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil)
          let uiImage = UIImage(CGImage: cgImage)
          let imageView = UIImageView(image: uiImage)
          cell.testPhoto.image = uiImage
      } catch  {
          print("Error generating thumbnail: \(error)")
      }
  
  }
  </code></pre>
  
  <p>How can I modify my code so that everything in the <code>do catch</code> block does not block the UI and works in the background?</p>
  
  <p>===EDIT</p>
  
  <p>after following your advices I modified my code so that now the <code>do-catch</code> statement is surrounded by dispatch:</p>
  
  <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
      var uiImage = UIImage()
      do {
          let asset = AVURLAsset(URL: NSURL(string: test.video)!, options: nil)
          let imgGenerator = AVAssetImageGenerator(asset: asset)
          imgGenerator.appliesPreferredTrackTransform = true
          let cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil)
          uiImage = UIImage(CGImage: cgImage)
          //let imageView = UIImageView(image: uiImage)
      } catch  {
          print("Error generating thumbnail: \(error)")
      }
  
      dispatch_async(dispatch_get_main_queue()) {
          cell.testPhoto.image = uiImage
      }
  }
  </code></pre>
  
  <p>now it seems to be working, but it does not cache the images and every time I scroll the table, it fetches the photos again... What's the best way to avoid it?</p>