AFNetworking:我如何获得NSMutableArray

时间:2013-09-19 16:57:09

标签: objective-c json afnetworking

我正在尝试修改Ray Wenderlich's tutorial以便从我的网上下载json文件,但是我被卡住了,因为这是我第一次使用AFNetworking。

我最好的尝试如下:

@interface LOArticulos (){
    NSData *jsonResponse;
}

@end

@implementation LOArticulos

+(LOArticulos *)sharedInstance{
    static LOArticulos *_sharedArticles;

    static dispatch_once_t once;
    dispatch_once(&once, ^{
        _sharedArticles = [[LOArticulos  alloc]init];
    });
    return _sharedArticles;
}

-(id)init{
    if (self = [super init]) {
        _todosLosArticulos = [self loadArticlesFromJSON];
    }
    return self;
}

- (NSArray *)loadArticlesFromJSON{

    NSURL *url = [NSURL URLWithString:@"http://www.xente.mundo-r.com/turkish/json/lakari.json"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                         JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
                                         {
                                             jsonResponse = JSON;
                                         }

                                         failure:^(NSURLRequest *request,NSHTTPURLResponse *response,NSError *error, id JSON)
                                         {
                                             NSLog(@"Request failed with error: %@, %@", error,error.userInfo);

                                         }];
     NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonResponse options:NSJSONReadingMutableContainers error:nil];

    [operation start];

    NSMutableArray *articlesArray = [[NSMutableArray alloc]initWithCapacity:jsonArray.count];

    for (NSDictionary *articleDictionary in jsonArray) {
        LOArticulo *articulo = [[LOArticulo alloc]init];
        articulo.ID = articleDictionary[@"id"];
        articulo.marca = articleDictionary[@"marca"];
        articulo.modelo = articleDictionary[@"modelo"];
        articulo.price = articleDictionary[@"precio"];
        articulo.categoria = articleDictionary[@"categoria"];
        articulo.photoURL = articleDictionary[@"photoUrl"];
        [articlesArray addObject:articulo];
    }        
    return articlesArray;
}

@end

不幸的是它不起作用,我收到以下错误:

因未捕获的异常而终止应用'NSInvalidArgumentException',原因:'数据参数为零'

拜托,你能帮助我吗?

由于

1 个答案:

答案 0 :(得分:1)

问题是jsonResponse在进入完成块时已经序列化为NSDictionary(或NSArray),而不是您期望的NSData。要解决此问题,请使用简单的AFHTTPRequestOperation,并使用您希望的任何选项自行序列化响应对象,例如NSJSONReadingMutableContainers