Running in the background is iOS

My app receives push notifications and occasionally does background fetches during which it issue queries over the REST api and does some updates. I’ve noticed in my logs that some queries are taking forever to run. For example, its not uncommon for the all_docs endpoint to take 800 seconds to load just 2 documents by id (using the keys parameter).

It also does things like writing to the file system, but so far that seems to behave normally.

Any idea as to what’s causing this?

It’s probably worth mentioning that this is what get’s called when the notification arrives:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  NSLog(@"notification-body => %@", notification);
  [RCTPushNotificationManager didReceiveRemoteNotification:notification];
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    NSLog(@"notification-complete => %@", notification);


My answer to performance issues like this is usually to get out some tools and measure what’s going on.

Can you run the app with Instruments, or attach Instruments to the running app when it’s in this state? (I have to say I’ve had only minimal experience using Instruments with on-device iOS apps.)

I’m not sure this is a performance question really, its more about how to get CBL to work when the app is in the background. Maybe more specifically, when its been resumed from the suspended state. The 800 seconds to load a couple of docs only happens when it’s in this state. Normally 2 documents can be loaded in around a second if the app is in the foreground. It’s as if CBL is stopping the queries from returning, or starting maybe.

Profiling will show what’s going on during that weird delay.

I don’t know enough about iOS programming to do any profiling. Besides which it’s almost impossible to reproduce because I think it only happens if the app has been suspended. When debugging though the app never gets suspended, and as far as I can see there’s no way to get Xcode to put the app into a suspended state. It’s just not reproducible in a dev situation, but happens all the time when the app is deployed ‘properly’. Very frustrating.

I think my didReceiveRemoteNotification implementation is wrong. I’ve done some reading and I think what I’m supposed to do is use beginBackgroundTaskWithName although its really not clear. I just want to give a app a little time to perform a few http requests (like a one-shot pull replication) after a push notification is received.

My theory about it being suspended was wrong. I still get huge delays when making the most simple queries of the app is running in the background… like over 12 seconds to retrieve one document by id.