0

在objective-c中处理这种情况的最佳方法是什么。在我对远程 API 的所有调用中,我需要确保我首先拥有令牌。如果可能的话,我宁愿在每次通话之前都不检查令牌。

DO NOT WANT TO DO THIS FOR EVERY API CALL!
#if (token) { 
   makeGetForTweetsRequestThatRequiresToken
 }

如果我需要一个令牌,也许它已过期,该调用可能需要一些时间才能返回,所以我需要等待它返回,然后再进行下一次 API 调用。是否可以执行以下操作?

[thing makeGetForTweetsRequestThatRequiresToken];


-(void)makeGetForTweetsRequestThatRequiresToken {
      if(nil == token) {

         // make another API call to get a token and save it
         // stop execution of the rest of this method until the
         // above API call is returned.

      } 

      //Do the makeGetForTweetsRequestThatRequiresToken stuff
}
4

1 回答 1

1

我认为您的令牌 API 将有一个回调。您可以注册一个块来处理该回调到您的 TweetsRequest API:

typedef void (^TokenRequestCompletionHandler)(BOOL success, NSString *token);

-(void) requestTokenCompletionHandler:(TokenRequestCompletionHandler)completionHandler
{
    //Call your token request API here.
    //If get a valid token, for example error==nil
    if (!error) {
        completionHandler(YES,token);
    } else {
        completionHandler(NO,token);
    }
}

在您的推文请求中:

-(void)makeGetForTweetsRequestThatRequiresToken {
  if(nil == token) {

     // make another API call to get a token and save it
     // stop execution of the rest of this method until the
     // above API call is returned.
     [tokenManager requestTokenCompletionHandler:^(BOOL success, NSString *token){
         if (success) {
           //Do the makeGetForTweetsRequestThatRequiresToken stuff

         } else {
           NSLog(@"Token Error");
         }
     }];
  } else {
    //You have a token, just Do the makeGetForTweetsRequestThatRequiresToken stuff
  }
}
于 2012-12-12T09:39:43.150 回答