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