完成块阻止AFJSONRequestOperation执行

时间:2013-08-24 10:18:54

标签: ios afnetworking

我正在使用AFNetworking lib检索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没有执行bloc,我在那里打印了一个日志,但是没有显示。 可能是什么问题呢? 非常感谢你。

1 个答案:

答案 0 :(得分:2)

抛弃此代码:

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

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

setDownloadProgressBlock中,只需按下主线程并更新您的UI即可。不要试图创建延迟,这只会导致明显的随机行为。另外,不要尝试使用下载结果,只能在success块中完成。