AFJSONRequestOperation

AFJSONRequestOperation

本文介绍了如何使用AFJSONRequestOperation返回响应对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AFJSONRequestOperation 获取天气数据。问题是查询完成后我无法返回对象。

I'm trying to get weather data by using AFJSONRequestOperation. The problem is I can't return the object when the query is done. Is there anyone know how to do that?

我当前的实现是

- (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 块内调用该块。

There is a way that you can do this, in a sense. Instead of having a traditional return method you can have the caller pass a block as a parameter, then you can call back to this block inside your success and failure AFJSONRequestOperation blocks.

以下是我的一些代码示例:

Here's an example from some of my code:

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

这篇关于如何使用AFJSONRequestOperation返回响应对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 06:00