如何使用AFJSONRequestOperation返回一个响应对象

我试图通过使用AFJSONRequestOperation获取天气数据。 问题是我不能在查询完成时返回对象。 有没有人知道如何做到这一点?

我目前的实施是

 - (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]; } 

从某种意义上说,你可以做到这一点。 而不是传统的返回方法,你可以让调用者传递一个块作为参数,然后你可以在你的成功和失败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 }