Requirements: Make two network requests at the same time, the network request is asynchronous, after the network request succeeds the other operation. Two network requests are so, a network request in the block after the execution, and then do other operations, it is the same principle, but this time does not need a thread group, only need to signal volume. Of course it applies to all blocks.
Next, let's say what happens after two asynchronous requests.
Use thread groups and semaphores to complete, see Code
-(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 [email protected]{
@ "lat": @ "40.04991291",
@ "lon": @ "116.25626162",
@ "APPID": Appidkey
};
Create a queue group so that two network requests can be executed asynchronously and then done
dispatch_group_t group = Dispatch_group_create ();
Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Create semaphore
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) {
Request successfully sent Semaphore (+1)
Dispatch_semaphore_signal (semaphore);
} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {
Send semaphores regardless of success or failure of the request (+1)
Dispatch_semaphore_signal (semaphore);
}];
Wait for semaphores before the request succeeds (-1)
Dispatch_semaphore_wait (semaphore, dispatch_time_forever);
});
Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Create semaphore
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) {
Send Signal Volume
Dispatch_semaphore_signal (semaphore);
} failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {
Send Signal Volume
Dispatch_semaphore_signal (semaphore);
}];
Wait for semaphores before the request succeeds
Dispatch_semaphore_wait (semaphore, dispatch_time_forever);
});
After the request is complete
Dispatch_group_notify (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
});
}
Other actions after block execution in IOS afnetworking