0

我正在尝试通过使用获取天气数据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];
}
4

1 回答 1

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
 }
于 2013-02-23T15:38:25.340 回答