2017-05-03 69 views
0

來調用API API我有如何使用NSURLSession塊

NSString* FBAuthoValue= @"TESTINGCONSTANT"; 

在Load按鈕的點擊,它調用HitLoadAPI

我打電話給我的API像下面HitLoadAPI,現在如果在我的服務器結束我的FBAuthoValue是我需要更改另一個API以獲取FBAuthoValue的刷新值並在HitLoadAPI中設置的更改。

1)用戶打HitLoadAPI與FBAuthoValue = @ 「TESTINGCONSTANT」 的價值,但作爲服務器現在FBAuthoValue = @ 「NewTestCode」,所以它返回httpresponsecode 909,對909我需要調用refreshFBAuthValue API,並把這個值回到HitLoadAPI,並且api工作正常。 2)如果FBAuthoValue標記在服務器中發生變化,需要調用refreshFBAuthValue API,並且其返回值需要設置並再次調用HitLoadAPI,而不需要知道用戶。

注意:我有打擊多個API此起彼伏,假設API-1,API-2,API-3等,如果FBAuthoValue,如果在任何API,在服務器的更改則需要刷新該FBAuthoValue,然後相同的API需要調用,而不影響或阻止用戶。 我肯定會獎勵50賞金。

概述:API-1調用,同時如果令牌過期,需要調用令牌過期api,並且API-1會再次調用,而無需用戶再次按Load按鈕。

這裏是我的代碼

-(void)HitLoadAPI 
{ 
NSError *error; 

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
NSURL *url = [NSURL URLWithString:@"[JSON SERVER"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy 
                timeoutInterval:60.0]; 

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:FBAuthoValue forHTTPHeaderField:FBAUTH]; 

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name", 
        @"IOS TYPE", @"typemap", 
        nil]; 
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error]; 
[request setHTTPBody:postData]; 
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields]; 
      //NSLog(@" headers =%@",headers); 
      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
      //NSLog(@"response status code: %ld", (long)[httpResponse statusCode]); 

      if([httpResponse statusCode]==909) 
       { 

       FBAuthoValue =[self refreshFBAuthValue]; 
       //what to do here so the current API hit will be call again.... 

       } 


}]; 

[postDataTask resume]; 
} 






-(NSString *) refreshFBAuthValue 
{ 
//hit api to get new refresh token code here need its calling code as well as the block coding cause it response so late which cause return value nil...to HitLoadAPI 
return FBaccess_token; //it will return refresh FBaccess_token code 

} 

回答

1

您可以創建可用於從應用程序中的任何地方調用任何API的方法,這種方法需要特定的參數通過API調用,如API URL,數據它將包含在請求的主體中,並且當fbAuthValue有效時將會調用一個完成塊。

-(void)HitAPILoadWithFbAuthValue:(NSString*)fbAuthValue apiUrl:(NSString*)apiUrl postData:(NSDictionary*)dict withCompletion:(void (^)(int statusCode,NSURLResponse * apiResponse,NSError * error))completion{ 
    NSError *error; 

     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
     NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 
     NSURL *url = [NSURL URLWithString:apiUrl]; 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                cachePolicy:NSURLRequestUseProtocolCachePolicy 
               timeoutInterval:60.0]; 

     [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
     [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
     [request setHTTPMethod:@"POST"]; 
     [request setValue: fbAuthValue forHTTPHeaderField:FBAUTH]; 

     //post body with dictionary passed as a parameter 
     NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error]; 
     [request setHTTPBody:postData]; 

     NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields]; 
     //NSLog(@" headers =%@",headers); 
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
     //NSLog(@"response status code: %ld", (long)[httpResponse statusCode]); 

     if([httpResponse statusCode]==909) 
      { 

      FBAuthoValue =[self refreshFBAuthValue]; 
      //what to do here so the current API hit will be call again.... 
      if (FBAuthoValue){ 
       [self HitAPILoadWithFbAuthValue:fbAuthValue apiUrl:apiUrl postData:dict withCompletion:completion]; 
      }else{ 
      } 

      } 
     //if FbAuthValue is valid, call completion block 
     completion((int)[httpResponse statusCode],response, error); 


    }]; 

     [postDataTask resume]; 
    } 

使用
我假設你寫在名爲APIManager一個單獨的類此方法。因此,要調用此方法首先創建一個APIManager的實例,並調用像這樣:

APIManager *sharedManager = [APIManager sharedInstance] 

    //call API_1 
    [sharedManager HitAPILoadWithFbAuthValue:FBAuthValue apiUrl:@"API_1_URL" postData:dict_for_first_api withCompletion:^(int statusCode, NSURLResponse *apiResponse, NSError *error) { 

    if(error != nil){ 
    //handle error here 
    }else{ 

     //call API_2 
     [sharedManager HitAPILoadWithFbAuthValue:FBAuthValue apiUrl:@"API_2_URL" postData:dict_for_second_api withCompletion:^(int statusCode, NSURLResponse *apiResponse, NSError *error) { 

     }]; 
    } 

}]; 
+0

我有一個所有API處理的公共類,如何做到這一點? – iphonemaclover

+0

同樣的方法將適用於每個方法遞歸調用匹配條件。並且方法中必須有一個退出點,以便它不會進入循環。 –

+0

need [self thismethodisnotfixe can change:FBAuthoValue]; – iphonemaclover