2012-12-12 52 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

相關問題