NSTimeInterval threadBlockInterval = 10.0;
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < 3; ++i) {
// enter 和 leave 必須成對出現(xiàn)
dispatch_group_enter(group);
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://www.itdecent.cn"]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle response
// 注意:
// 當(dāng)前的線程和調(diào)用線程不是一個(gè)線程,更不能返回調(diào)用線程做操作,會死鎖的。
// 因?yàn)?,AFNetworking completionBlock 是返回 main thread 調(diào)用的,
// 所以,如果調(diào)用線程就是 main thread 的話是不能使用 AFNetworking 的
dispatch_group_leave(group);
}];
[task resume];
}
dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, threadBlockInterval * NSEC_PER_SEC));
注意:
- 如果想在 main thread 發(fā)送同步請求,不能使用
AFNetworking - 如果網(wǎng)絡(luò)做了緩存的話,也就是 completionHandler 可能會調(diào)用
>=2次,在dispatch_group_leave那里需要做判斷,enter和leave調(diào)用次數(shù) 必須 保持一致