복수 비동기 요청을 수행하기 위해 NSURLConnection
을 사용하고 있습니다. 수행해야 할 총 숫자에서 완료된 요청 수를 보여주는 진행률 표시기를 보여 드리고자합니다. 그러나 요청을 만들기 전에이 진행률 표시기를 설정하고 표시하려고하거나 요청을 수행하기 전에 호출 된 다른 메서드에서 표시하려고하면 표시되지 않습니다. 요청이 주석 처리되면 진행률 표시기가 잘 표시됩니다. 그러나 그렇지 않은 경우 Xcode는 비동기 요청을 받고 기본 스레드를 차단하여 UI 변경을 불가능하게하는 것처럼 보입니다. 비동기 요청의 블록 주석NSURLConnection sendAsynchronousRequest : 메인 스레드 차단
- (void)getRegionalInformationFromChecked:(NSSet *)set atIndex:(NSInteger)index {
__block BOOL responseRecieved = NO;
NSString *stringForURL = [NSString stringWithFormat:@"http://www.thebluealliance.com/api/v1/event/details?event=%@",[[set allObjects] objectAtIndex:index]];
NSURL *url = [NSURL URLWithString:stringForURL];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(@"URL IS GO: %@", stringForURL);
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:queue completionHandler:^(NSURLResponse *_response, NSData *_data, NSError *_error) {
NSLog(@"CHECKED DATA RETURNED AT INDEX %i", index);
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:&error];
if (!_regionalDetails) {
_regionalDetails = [[NSMutableArray alloc] init];
}
[_regionalDetails addObject:dict];
responseRecieved = YES;
}];
regionalSchedulesToGet = [set count];
while (responseRecieved == NO) {}
[[MBProgressHUD HUDForView:[[UIApplication sharedApplication] keyWindow]] setLabelText:[NSString stringWithFormat: @"Getting regional %i of %i", index+2, [set count]]];
if (index+1 < [set count]) {
[self getRegionalInformationFromChecked:set atIndex:index+1];
} else {
[[MBProgressHUD HUDForView:[[UIApplication sharedApplication] keyWindow]] setLabelText:@"Writing to file"];
}
}
에서, MBProgressHUD
이 값 벌금을 표시
다음은 진행 상태를 표시하는 요청 및 코드를 모두 포함하여, 호출되는 관련 코드입니다. 그러나 블록을 삽입하면 SDK는 블록을 벗어난 후에도 진행률 표시기를 업데이트하지 않습니다. 이후 스레드 문제가 해결되어야합니다. 더 이상 표시 할 요청이 없으면 "파일에 쓰는 중"이라는 메시지가 표시 될 때까지 업데이트되지 않습니다.
왜 비동기 요청이 주 스레드를 차단하는 것처럼 보이고 요청이 호출되기 전이나 후에 주 스레드에서 변경을 수행 할 수없는 이유는 무엇입니까?
스레드를 차단하지 않습니다. 메인 스레드에서 UIKit을 호출하지 않기 때문에 프로그램이 UB를 호출한다는 것입니다. –
흠. 나는 또한'dispatch_sync()'를 사용하여 메인 큐를 얻고 아무 쓸모없는 UI를 업데이트하려고했다. –