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

4

1 回答 1

0

因为您在completionHandler(UIBackgroundFetchResultNewData);之后立即调用(这表明您的后台获取已完成)[self startOAuth2];,因此无需等待您的委托被调用。

您需要找到一种方法来调用completionHandler(UIBackgroundFetchResultNewData);- (void)auth:(GTMOAuth2Authentication *)auth finishedRefreshWithFetcher:(GTMHTTPFetcher *)fetcher error:(NSError *)error方法。

于 2015-08-21T08:55:09.603 回答