我正在使用 AFNetworking 库检索 JSON 数据,并想添加一个完成 block ,如下所示:
-(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];
}
当我添加完成 block 时,我不再有结果,屏幕上没有显示任何内容,并注意到 AFJSONRequestOperation
block 没有执行,我在那里打印了一个日志,但没有显示。
可能是什么问题呢?
非常感谢。
最佳答案
扔掉这段代码:
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Completed:");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
相反,将您的日志记录放入 JSONRequestOperationWithRequest:success:failure:
上的 block (您当前有一个成功 block 但没有失败 block ,并且成功 block 正在被删除的代码删除你应该删除)。
在 setDownloadProgressBlock
中,只需推送到主线程并更新您的 UI。不要试图制造延迟,这只会导致明显的随机行为。另外,不要尝试使用下载的结果,这应该只在 success
block 中完成。
关于ios - 完成 block 阻止 AFJSONRequestOperation 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417463/