我有一个 UITableViewController
从工作正常的 WS json 中获取它的信息。
现在我需要在 UIRefreshControl
上使用两个不同的 WS 调用来填充表格和表格的标题 View 。拉。
-(void)refreshView:(UIRefreshControl *)refresh {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__block NSData *data = [self fetchNewData];
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
[self fetchedData:data];
[self.tableView reloadData];
} else {
//show error
}
[self.refreshControl endRefreshing];
});
});
}
-(NSData*)fetchNewData {
NSString *api = SINGLE URL;
if (api) {
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:api]];
return data;
} else {
return nil; //alert
}
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error = nil;
_JSONDict = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
_tableDataRows = [_JSONDict objectForKey:@"tableDataRows"];
}
}
最后,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
使用 _tableDataRows
填充表格。现在,我想在
UIRefreshControl
的同一“拉”上更新表头 View 上的一些标签,这是来自 ViewController 的自定义 View ,来自第二个 API URL json ,这意味着加载动画应该一直打开,直到两个 json 都被下载和解析。最好的方法是什么?如果您需要更多信息,请告诉我..
谢谢!
最佳答案
在阅读了@Greg 的评论链接和其他问题后:Waiting until two async blocks are executed before starting another block
我想出了这个以我想要的方式工作的方法:
-(void)refreshView:(UIRefreshControl *)refresh {
dispatch_group_t group = dispatch_group_create();
__block BOOL isReachable = NO;
__block NSData *data = nil;
__block NSData *dataPublic = nil;
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
isReachable = [self.appDelegate isReachable];
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
if (isReachable) {
data = [self fetchNewData];
}
});
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
if (isReachable) {
dataPublic = [self fetchPublicData];
}
});
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
if (isReachable) {
dispatch_async(dispatch_get_main_queue(), ^{
//Public data
if (dataPublic) {
[self fetchedPublicData:dataPublic];
} else {
//handle error
}
//User data
if (data) {
[self fetchedData:data];
[self.tableView reloadData];
} else {
//handle error
}
[self.refreshControl endRefreshing];
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.refreshControl endRefreshing];
[self.appDelegate showConnectionErrorAlert];
});
}
});
}
请随时提出改进建议!
关于ios - UIRefreshControl 与两个异步 json 下载来填充 UITableView 行和自定义标题 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20199946/