iOS-ネットワーク要求の同時および同期

2510 ワード

複数のネットワークリクエストを並列またはシリアルで実行した後、プライマリ・スレッドに戻っていくつかの操作を実行する必要がある場合があります.この場合、dispatch_を使用してsemaphoreはこの機能を実現するために,次の3つのネットワーク要求をシミュレートし,実際のNSUrlSessionでの方法自体が非同期であるため,非同期スレッドを開く必要はない.
    __block NSString *string1;
    __block NSString *string2;
    __block NSString *string3;
    
//     
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [NSThread sleepForTimeInterval:8];
//        string1 = @" 1";
//        NSLog(@" 1-start");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [NSThread sleepForTimeInterval:5];
//        string2 = @" 2";
//        NSLog(@" 2-start");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [NSThread sleepForTimeInterval:5];
//        string3 = @" 3";
//        NSLog(@" 3-start");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    NSLog(@"%@-%@-%@",string1,string2,string3);
    
//     
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:8];
        string1 = @" 1";
        NSLog(@" 1-start");
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:5];
        string2 = @" 2";
        NSLog(@" 2-start");
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:5];
        string3 = @" 3";
        NSLog(@" 3-start");
        dispatch_semaphore_signal(semaphore);
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"%@-%@-%@",string1,string2,string3);