Search code examples
iosblock

Completion handler was never called?


When this method (application:didReceiveRemoteNotification:fetchCompletionHandler:) is done, now how should I call the completionHandler block?

As the document describes that "In practice, your app should call the handler block as soon as possible after downloading the needed data."


Solution

  • For example:

    - (void)application:(UIApplication *)application 
    didReceiveRemoteNotification:(NSDictionary *)userInfo 
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler 
    {
        // Based on the provided meta data in userInfo, load the resource from our 
        // server which corresponds to the "updated" information:
    
        NSDictionary* params = ; // based on userInfo
        [self fetchInfoWithParams:params completion:^(NSData* result, NSError* error){
            UIBackgroundFetchResult fetchResult;
            if (error) {
                fetchResult = UIBackgroundFetchResultFailed;
            }
            else if (result) {
                fetchResult = UIBackgroundFetchResultNewData;
            }
            else {
                // data is nil
                fetchResult = UIBackgroundFetchResultNoData;
            }
    
            // call the handler (if any):
            if (handler) {
                handler(fetchResult);
            }
        }];
    }