2012-12-12 117 views
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 
} 

回答

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 
    } 
} 
+0

你有completionHandler(YES,令牌);两次? – jdog

+0

我很抱歉。编辑!谢谢 – onevcat

相关问题