2013-02-23 2 views
0

AFJSONRequestOperation을 사용하여 기상 데이터를 가져 오려고합니다. 문제는 쿼리가 완료 될 때 개체를 반환 할 수 없다는 것입니다. 그걸하는 법을 아는 사람이 있습니까?AFJSONRequestOperation을 사용하여 응답 개체를 반환하는 방법

나의 현재 implemation는 의미에서,이 작업을 수행 할 수있는 방법이 있습니다

- (NSDictionary *)getCityWeatherData:(NSString*)city 
{ 
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxx&num_of_days=3&format=json&q=%@", city]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     NSDictionary *data = [[JSON objectForKey:@"data"] objectForKey:@"weather"]; 
     return data; 
    } failure:nil]; 
    [operation start]; 
} 
+0

확인이 다른 질문 http://stackoverflow.com/questions/7969865/can- 여기

내 코드의 일부에서 예입니다 afnetworking-return-data-synchronous-inside-a-block – tkanzakic

답변

0

입니다. 호출자가 블록을 매개 변수로 전달하도록 할 수있는 전통적인 반환 방법 대신 성공 및 실패 내에서이 블록으로 다시 호출 할 수 있습니다. AFJSONRequestOperation 블록.

- (void)postText:(NSString *)text 
    forUserName:(NSString *)username 
    withParameters:(NSDictionary *)parameters 
     withBlock:(void(^)(NSDictionary *response, NSError *error))block 
{ 
    NSError *keychainError = nil; 
    NSString *token = [SSKeychain passwordForService:ACCOUNT_SERVICE account:username error:&keychainError]; 

    if (keychainError) { 
     if (block) { 
      block([NSDictionary dictionary], keychainError); 
     } 
    } else { 
     NSDictionary *params = @{TEXT_KEY : text, USER_ACCESS_TOKEN: token}; 
     [[KSADNAPIClient sharedAPI] postPath:@"stream/0/posts" 
            parameters:params 
            success:^(AFHTTPRequestOperation *operation, id responseObject) 
     { 
      if (block) { 
       block(responseObject, nil); 
      } 
     } 
            failure:^(AFHTTPRequestOperation *operation, NSError *error) 
     { 
      if (block) { 
       block([NSDictionary dictionary], error); 
      } 
     }]; 
    } 
} 

내가이 그것을 호출 :

[[KSADNAPIClient sharedAPI] postText:postText 
          forUserName:username 
         withParameters:parameters 
          withBlock:^(NSDictionary *response, NSError *error) 
{ 
     // Check error and response 
} 
관련 문제