1

I have a background fetch that updates my local sqlite data.

If the app is also running in the foreground, I want to be able to detect if the background fetch is running in order to stop the UI attempting to load partially populated sql rows.

How can I detect if a background fetch is running?

Also, is there a better ui pattern than telling the user that they can't view the data?

DEzra
  • 2,978
  • 5
  • 31
  • 50
  • Perhaps you could manipulate a variable in your app delegate to indicate the start and end of background fetch... If you need more help, please post your background fetch code. – Lyndsey Scott Dec 21 '14 at 14:46

2 Answers2

0

You can check the application's state

[UIApplication sharedApplication].applicationState

There are three possible options

UIApplicationStateActive
UIApplicationStateInactive
UIApplicationStateBackground

If you need to check whether it's the UI thread, try this

if ([NSThread isMainThread])
{
    // main thread
}
SomeGuy
  • 9,670
  • 3
  • 32
  • 35
  • Ok, so you are suggesting I put check in the background fetch code. Which would then need additional checks to see if the app is on a 'display data' screen. Is there a way of detecting that background fetch is running FROM the UI thread? – DEzra Dec 21 '14 at 13:06
  • @DEzra I didn't actually think the background fetch tasks could be run from any state other than the background, but if so then that code will tell you the app's state. I've also updated my answer to show how to indicate which thread your code is running on. – SomeGuy Dec 21 '14 at 13:10
  • thanks for the update, I'm not sure either. But I do know that it's possible that a background thread could be running a fetch whilst the app is also running (in different threads), as the simulator allows your to simulator that. – DEzra Dec 21 '14 at 13:25
0

It sounds like you should be doing your background fetch with a different managed object context from your UI managed object context.

You would save your background context when the data is consistent and available for display, and use the didSaveContextNotification to merge the changes into your UI context and update the display.

Your background fetch would not have to know anything about the UI logic. The UI logic would only have to know that it should update after the data has changed due to a merge.

Matt
  • 4,261
  • 4
  • 39
  • 60