0

我正在使用 AFNetworking 库检索 JSON 数据,并希望添加一个完成块,如下所示:

-(void)getData{

    NSString *link=@"http://localhost:8080/address/address/address/";

    NSURL *url= [ NSURL URLWithString:link];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        arrayofA=[JSON valueForKeyPath:@"a"];
        arrayofB=[JSON valueForKeyPath:@"b"];


        [[self techTableView] reloadData];

    } failure:nil];


    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        //-- This block gets invoked periodically as the download progress

        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(totalBytesRead * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){

            dispatch_async(dispatch_get_main_queue(), ^{
                // HUD treatment
            });
        });



    }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Completed:");

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);

    }];

    [operation start];

}

当我添加完成块时,我不再有结果,屏幕上没有显示任何内容,并注意到AFJSONRequestOperation块没有执行,我在那里打印了一个日志,但它没有显示。可能是什么问题呢?非常感谢你。

4

1 回答 1

2

扔掉这段代码:

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Completed:");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

相反,将您的日志记录到JSONRequestOperationWithRequest:success:failure:(您当前有一个成功块但没有失败块,并且成功块正在被您应该删除的代码删除)的块中。

setDownloadProgressBlock中,只需推送到主线程并更新您的 UI。不要费心试图制造延迟,这只会导致明显的随机行为。另外,不要尝试使用下载的结果,这只能在success块中完成。

于 2013-08-24T13:29:32.317 回答