iOSの複数の画像を並列にアップロードするサーバ

1538 ワード




- (IBAction)runDispatchTest:(id)sender {
    //  
    NSArray* images = [self images];
    
    //  , ,  NSNull  
    NSMutableArray* result = [NSMutableArray array];
    for (UIImage* image in images) {
        [result addObject:[NSNull null]];
    }
    
    dispatch_group_t group = dispatch_group_create();
    
    for (NSInteger i = 0; i < images.count; i++)
    {
        
        dispatch_group_enter(group);
        
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSURLSessionUploadTask* uploadTask = [self uploadTaskWithImage:images[i] completion:^(NSURLResponse *response, NSDictionary* responseObject, NSError *error) {
                if (error)
                {
                    NSLog(@"  %d  : %@", (int)i + 1, error);
                
                } else
                {
                    NSLog(@"  %d  : %@", (int)i + 1, responseObject);
                    @synchronized (result)
                    { // NSMutableArray  , 
                        result[i] = responseObject;
                    }
               
                }
                
                dispatch_group_leave(group);
            }];
            [uploadTask resume];
            
        });
       
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@" !");
        for (id response in result) {
            NSLog(@"%@", response);
        }
    });
}