I'm working on an iOS app now and I want to do the following thing: when the user launches the app, it starts downloading a file from network and then saves it to a local Core Data database. I know how to download files and work with Core Data. I just want it to be done in background while the user might be navigating through the app.
-
1Refer this link for perform longer running tasks in background: [Performing Background Tasks in iOS](http://stackoverflow.com/questions/5323634/ios-application-executing-tasks-in-background) – Aamir Jan 06 '16 at 10:15
-
perform these tasks on a background thread using dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ }); – nsinvocation Jan 06 '16 at 10:18
2 Answers
You can do it like this
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
println("This is run on the background queue")
dispatch_async(dispatch_get_main_queue(), {
println("This is run on the main queue, after the previous block")
})
})
If you are using NSURLSession
tasks for the download, this will happen in the background in any case. If you use a completion handler, it will also be called in the background, where you can do processing of the file (e.g. JSON decoding).
The trickier part is related to the Core Data updates. The simple solution is to do this in the foreground, by encapsulating all Core Data updates in dispatch_async(dispatch_get_main_queue()) { ... }
blocks (or using performBlock:
), but if you have a larger number of updates that will block the UI quite a bit while this is done.
The other alternative is to make sure you use a dedicated Core Data context with concurrency type NSPrivateQueueConcurrencyType
, and make sure all updates are performed on that context via performBlock:
. When you finally save this context (which pushes the changes to the main context), you should also save the main context to save changes.

- 17,302
- 6
- 32
- 46