http://www.cnblogs.com/stoic/archive/2012/09/25/2785184.html
- (void)getData
{
NSString *appIdKey = @"8781e4ef1c73ff20a180d3d7a42a8c04";
NSString* urlString_1 = @"http://api.openweathermap.org/data/2.5/weather";
NSString* urlString_2 = @"http://api.openweathermap.org/data/2.5/forecast/daily";
NSDictionary* dictionary =@{
@"lat" : @"40.04991291",
@"lon" : @"116.25626162",
@"APPID" : appIdKey
};
// 创建队列组,可以使两个网络请求异步执行,执行完之后再进行操作
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
[mgr GET:urlString_1 parameters:dictionary progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// 请求成功发送信号量(+1)
dispatch_semaphore_signal(semaphore);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// 无论请求成功或失败都发送信号量(+1)
dispatch_semaphore_signal(semaphore);
}];
// 在请求成功之前等待信号量(-1)
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 创建信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
[mgr GET:urlString_2 parameters:dictionary progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// 发送信号量
dispatch_semaphore_signal(semaphore);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// 发送信号量
dispatch_semaphore_signal(semaphore);
}];
// 在请求成功之前等待信号量
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
});
// 请求完成之后
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
}