title: CoreData Save Context Causing Crash When App Returns to Foreground. Swift
body: <p>Okay so I am experiencing a frustrating issue that I would love some help or advice with.  Basically I have an app that I'm developing that utilizes <code>Core Data</code> to store numerous user properties.  What I have been doing for months during development, is I will save the <code>managedObjectContext</code> whenever the user transitions from active state to the background.  I use some background fetch requests, so I was a told to exclusively use the <code>applicationDidEnterBackground</code> in the <code>AppDelegate</code> instead the <code>applicationWillTerminate</code> function. Essentially I'm doing something similar to this:</p>
  
  <pre><code>func applicationDidEnterBackground(application: UIApplication) {
  
      if !userSaved {
          saveUserDataLocally()
      }
  
  }
  
  func saveUserDataLocally() {
  
      // Handle all the data, store it properly in managedObjectContext
      // .........
      // .......
      do {
          try managedObjectContext.save()
          print("Success on save")
      } catch let error {
          print("Error saving user \(error)")
      }
  
  }
  </code></pre>
  
  <p>Now this has been working just fine for months when I test the app on my iPhone through xCode. And it still works fine whenever I push the app into the background, and wait a few seconds for the save to the <code>managedObjectContext</code> to complete (sometimes it can take 3-4 seconds if there is a lot of data being stored).  My problem arises ONLY when I test the app NOT through xCode.  So if I have the app installed on my phone, and just try testing it while riding the bus to school I experience an issue.  And it only causes a crash when I push the app into background mode, and then instantly tap the app's icon on the home screen to launch it again (as if I accidentally tapped the home button to push it into the background). The same goes for if I'm not testing through xCode and try to force quit the app. In that circumstance it doesn't crash because the app isn't running, but it never completes the save.</p>
  
  <p>I've tried tirelessly to recreate this problem while having my phone plugged into my computer and testing it through xCode, that way I could install break points and find the root of the issue. This problem NEVER exists when testing through xCode.  When I test it then, I can push the app to the background, and then half a second later launch it back up, and not only does the original save request complete, but it doesn't cause a crash.  Also I can force quit the app while running it through xCode and it will allow the save to complete, then the app will terminate. </p>
  
  <p>As I'm sure you can imagine, this is very frustrating because if I can't recreate the problem while using the debugging tools xCode provides, I have a really hard time finding the source of the bug. Just to play it safe, I made sure numerous times that nothing is being called in the <code>AppDelegate</code>'s <code>applicationWillEnterForeground</code> or <code>applicationDidBecomeActive</code> methods.  I'm totally lost.  It seems to me that by pushing the app back to the foreground while it is in the middle of saving the <code>managedObjectContext</code>, it's getting confused and crashing...but then why doesn't that happen when I test the app on my device while using xCode?</p>
  
  <p>Can anybody help me with this?  I may not have any hair left in a few hours! ;-)</p>
  
  <p>|||   <strong>UPDATE 06/03</strong>   |||</p>
  
  <p>So with the help of some commenters, I was able to find that part of the issue is due to the <code>CoreData</code> request clogging up the main thread, and then causing the app to stop responding.  I'm not sure that this is the exact solution to my specific problem, but is definitely helpful towards recognizing the issue completely.  One of the reasons I tried to do all my saving while transitioning into the background, was because I was executing all my saves on the main thread, and when I would perform a save during the app usage, it would cause a delay or bog down the main thread.  I've been experimenting with doing saves executing on a background thread, and it's helping tremendously.  Doing so, I can save my user data in the background while the other parts of the app are running, and it doesn't clog the main thread.  This helps make it so I don't even need to save while transitioning to background, so the crash won't happen anymore.</p>
  
  <p>I found an amazing tutorial for executing background thread requests for <code>CoreData</code> by somebody named Justin Driscoll on themainthread.com</p>
  
  <p>Check out this site if you are looking for help in executing <code>CoreData</code> requests in the background: <a href="http://themainthread.com/blog/2015/08/core-data-stack-in-swift.html" rel="noreferrer">http://themainthread.com/blog/2015/08/core-data-stack-in-swift.html</a></p>
  
  <p>|||   <strong>FURTHER UPDATE</strong>   |||</p>
  
  <p>For those who are possibly in need of help with a similar issue.  I used Mr. Driscoll's tutorial to create a <code>NSManagedObjectContext</code> that would save on a background thread. Even after I did everything, it was still executing everything on the main thread, and I was going insane.  I found one little thing that was very important: to make sure your save executes outside the main thread, set the proper concurrency type.  For example: </p>
  
  <pre><code>let concurrencyType:NSManagedObjectContextConcurrencyType = .PrivateQueueConcurrencyType
  
  managedObjectContext = NSManagedObjectContext(concurrencyType: concurrencyType)
  </code></pre>
  
  <p>Once I changed that one little thing, my save request would execute on the background thread and now my main thread was free to do UI updates and what not.  Hope this helps anybody experiencing similar frustrations!</p>