iOS 使用信号量实现多层循环的网络请求
Posted 夏天然后
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 使用信号量实现多层循环的网络请求相关的知识,希望对你有一定的参考价值。
- (void)start
dispatch_async(dispatch_get_global_queue(0, 0), ^
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
for (int i = 0; i < users.count; i ++)
NSString *url = [NSString stringWithFormat:reposListUrl, users[i]];
// 请求每个用户的所有库
[XTNetwork requestWithURL:url parameter:nil methods:GET successResult:^(id result)
NSArray *data = result;
NSMutableArray *names = [NSMutableArray array];
for (int i = 0; i < data.count; i ++)
NSDictionary *dic = data[i];
NSString *name = dic[@"name"];
[names addObject:name];
NSLog(@"第一层的 i = %d", i);
dispatch_async(dispatch_get_global_queue(0, 0), ^
dispatch_semaphore_t semaphore1 = dispatch_semaphore_create(0);
for (int j = 0; j < names.count; j ++)
NSString *detailUrl = [NSString stringWithFormat:reposDetailUrl, users[i], names[j]];
[XTNetwork requestWithURL:detailUrl parameter:nil methods:GET successResult:^(id result)
NSLog(@"第二层的 i = %d, j = %d", i, j);
dispatch_semaphore_signal(semaphore1);
];
dispatch_semaphore_wait(semaphore1, DISPATCH_TIME_FOREVER);
dispatch_semaphore_signal(semaphore);
);
];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
);
2023-01-13 20:38:26.257297+0800 XTWeibo[3158:204344] 第一层的 i = 0
2023-01-13 20:38:26.261531+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 0
2023-01-13 20:38:27.276864+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 1
2023-01-13 20:38:28.051853+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 2
2023-01-13 20:38:29.074902+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 3
2023-01-13 20:38:29.794057+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 4
2023-01-13 20:38:30.509545+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 5
2023-01-13 20:38:31.227020+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 6
2023-01-13 20:38:31.943710+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 7
2023-01-13 20:38:32.641432+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 8
2023-01-13 20:38:33.376847+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 9
2023-01-13 20:38:34.093713+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 10
2023-01-13 20:38:34.914586+0800 XTWeibo[3158:204344] 第二层的 i = 0, j = 11
2023-01-13 20:38:35.992519+0800 XTWeibo[3158:204344] 第一层的 i = 1
2023-01-13 20:38:37.264356+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 0
2023-01-13 20:38:37.985781+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 1
2023-01-13 20:38:39.314381+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 2
2023-01-13 20:38:40.133719+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 3
2023-01-13 20:38:41.057140+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 4
2023-01-13 20:38:42.182486+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 5
2023-01-13 20:38:43.219709+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 6
2023-01-13 20:38:44.025821+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 7
2023-01-13 20:38:44.844844+0800 XTWeibo[3158:204344] 第二层的 i = 1, j = 8
以上是关于iOS 使用信号量实现多层循环的网络请求的主要内容,如果未能解决你的问题,请参考以下文章