0

My app performs a background fetch, in which it does a series of communications with a web service, and posts local notifications if there's some new information.

I have an umbrella method, called GetEverything, that starts this chain of logging in, getting, posting, processing data, etc. This is the method that is called upon a background fetch.

GetEverything can also be triggered by a user in the foreground. In that case it always works as expected.

When GetEverything is called from the background fetch, is gets stuck on individual parts of the GetEverything chain. Some of the spawned threads just hang. Only when I bring the app to the foreground, they resume.

To solve this, I forced GetEverything to a low-prio thread:

- (void)GetEverything:(void (^)(BOOL))completionHandler{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       //my chain of events;

    });
}

That helped a lot, but still, I had to get deeper into the chain, to pinpoint other methods, and force them on low priority as well.

One example of a method in my chain that pops back to the main thread is

-(NSString*) deleteHTMLfrom: (NSString*) htmlString {         
    if (![htmlString isKindOfClass:[NSNull class]]){


        NSAttributedString* attributedText = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
                                                                              options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                                        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                                   documentAttributes:nil
                                                                                error:nil];
        NSString* plainText = [attributedText string];
        return plainText;
    }
    return htmlString;
}

My question: how to I force all the 'links' of my chain to perform on a background thread?

Sjakelien
  • 1,999
  • 2
  • 21
  • 38
  • 1
    Have you called `beginBackgroundTaskWithExpirationHandler` before you call `getEverything`? – Paulw11 Jun 27 '17 at 07:30
  • @Paulw11 I guess that my lack of knowledge of this is the reason for my question. I'm reading documentation right now. Would beginBackgroundTaskWithExpirationHandler be the magic trick that I need? – Sjakelien Jun 27 '17 at 07:33
  • You need to ensure that all of your tasks are finished before you return from the background fetch delegate method, and if they haven't then you need to have told iOS that background tasks are still running - see https://stackoverflow.com/questions/39197933/how-to-troubleshoot-ios-background-app-fetch-not-working/39219264#39219264 – Paulw11 Jun 27 '17 at 07:42

0 Answers0