0

我正在尝试修改Ray Wenderlich 的教程,以便从我的网站下载一个 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'而终止应用程序,原因:'数据参数为零'

拜托,你能帮帮我吗?

谢谢

4

1 回答 1

1

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

于 2013-09-19T17:01:16.260 回答