0

I am trying to check emails on gmail while app is in background.

I have to deal with OAuth2 to get to the gmail, so 1st I am refreshing the token. Then in finishedRefreshWithFetcher, if no error I am checking emails using Mailcore2.

It all works fine if app is in foreground, or in -(void) applicationDidBecomeActive: (UIApplication *) application {...}.

But in background fetch it never gets to -(void)auth:finishedRefreshWithFetcher:error:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [self startOAuth2];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void) startOAuth2{
    static NSString *const kKeychainItemName = @"Google OAuth2 For MyApp";
    static NSString *const kClientID = @"***";
    static NSString *const kClientSecret = @"***";    
    GTMOAuth2Authentication * auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName clientID:kClientID clientSecret:kClientSecret];
    if ([auth refreshToken] != nil) {
        [auth beginTokenFetchWithDelegate:self didFinishSelector:@selector(auth:finishedRefreshWithFetcher:error:)];
    }
}
- (void)auth:(GTMOAuth2Authentication *)auth finishedRefreshWithFetcher:(GTMHTTPFetcher *)fetcher error:(NSError *)error {
     if (error != nil) {// Refresh failed
         return;
     }
     [self retrieveEmails];
}

I can store token and just reuse it w/o refresh, i.e. just skip startAuth2 and go straight to retriveEmails and it all works fine too, but not sure if it is safe.

Thanks

Boris Gafurov
  • 1,427
  • 16
  • 28

1 Answers1

0

Because you're calling completionHandler(UIBackgroundFetchResultNewData); (which tells that your background fetch is done) immediatly after [self startOAuth2]; and thus without waiting for your delegate to be called.

You need to find a way to call completionHandler(UIBackgroundFetchResultNewData); in the - (void)auth:(GTMOAuth2Authentication *)auth finishedRefreshWithFetcher:(GTMHTTPFetcher *)fetcher error:(NSError *)error method.

Yaman
  • 3,949
  • 4
  • 38
  • 60