Reputation: 3137
I'm retrieving JSON data using AFNetworking lib, and wanted to add a completion block as follows:
-(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];
}
When I added the completion bloc I no longer have a result, nothing is shown in the screen, and noticed that AFJSONRequestOperation
bloc is not executed, I printed a log there and it's not shown.
What could be the problem?
Thank you very much.
Upvotes: 0
Views: 169
Reputation: 119041
Throw this code away:
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Completed:");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
Instead, put your logging into the blocks on the JSONRequestOperationWithRequest:success:failure:
(where you currently have a success block but no failure block, and the success block is being removed by the code that you should remove).
In setDownloadProgressBlock
, just push to the main thread and update your UI. Don't bother trying to create a delay, that will only lead to apparently random behaviour. Also, don't try to use the result of the download, that should only be done in the success
block.
Upvotes: 2