我得到了n个json数据,一旦整个内容被下载或者获得json的过程完成,我需要更新tableView的UI
for(int i = 1;i <= self.numberOfEpisodes;i++)
{
NSString *endPoint = [[[[urlJson stringByAppendingString:getEpisodes]stringByAppendingString:title]stringByAppendingString:@"&episodeNumber="]stringByAppendingString:[NSString stringWithFormat:@"%i",i]];
endPoint = [endPoint stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"End point %@",endPoint);
[downloadJson:endPoint WithHandler:^(__weak id result)
{
NSArray *episodeArray =result;
if(episodeArray && episodeArray.count > 0)
{
for(NSDictionary *dictionary in episodeArray)
{
//parse stuff here
}
}
if(i == self.numberOfEpisodes)
{
//update UI
}
}];
}
问题在于此行 if(i == self.numberOfEpisodes)。我不知道为什么整数 i 没有从1排列到self.numberOfEpisodes。相反,它是从1到self.numberOfEpisodes的随机数。那么有另一种方法来检查json的获取是否完整?
(void)getJson:(NSString *)urlString WithHandler:(void(^)(__weak id result))handler
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setHTTPMethod:@"GET"];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
id returnedObject = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error:nil];
handler(returnedObject);
}
else{
NSLog(@"error %@",error);
}
}];
[dataTask resume];
}
答案 0 :(得分:0)
是的,dispatch_group_t
//Creat group
dispatch_group_t group = dispatch_group_create();
for(int i = 1;i <= self.numberOfEpisodes;i++)
{
//Enter group
dispatch_group_enter(group);
NSString *endPoint = [[[[urlJson stringByAppendingString:getEpisodes]stringByAppendingString:title]stringByAppendingString:@"&episodeNumber="]stringByAppendingString:[NSString stringWithFormat:@"%i",i]];
endPoint = [endPoint stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSLog(@"End point %@",endPoint);
[downloadJson:endPoint WithHandler:^(__weak id result)
{
NSArray *episodeArray =result;
if(episodeArray && episodeArray.count > 0)
{
for(NSDictionary *dictionary in episodeArray)
{
//parse stuff here
}
}
// Then Leave group
dispatch_group_leave(group);
}];
}
//Here you will be notified after it's done
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// Do whatever you need to do when all requests are finished
//Update UI
});