Use dispatch_group_t, dispatch_group_enter dispatch_group_leave, dispatch_group_notify.
Also, below is code to send a huge array to server by dividing ti to parts. It is actual when a single request is too big for server – you get “URL too long error” or HTTP 414.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
- (void)divideAndSendContacts:(NSArray *)contactsArray { [self showSpinner]; dispatch_group_t group = dispatch_group_create(); NSInteger maxContactsInOneRequest = 29; NSInteger totalCount = [contactsArray count]; // Округляем в большую сторону по формуле A/B = (A+B-1)/B, например (700 + 300 - 1)/300 = 3.33 = 3. NSInteger numberOfParts = (totalCount + maxContactsInOneRequest - 1) / maxContactsInOneRequest; for (int i = 0; i < numberOfParts; i++) { NSRange range = NSMakeRange(i * maxContactsInOneRequest, maxContactsInOneRequest); NSInteger lastItemIndex = i * maxContactsInOneRequest + maxContactsInOneRequest; // Например, i=3, 29*3+29=116. Больше 100, поэтому вместо 29 берем 100-29*3=13 if ( lastItemIndex > totalCount ) { NSInteger length = totalCount - i * maxContactsInOneRequest; range = NSMakeRange(i * maxContactsInOneRequest, length); } NSArray *contactsArrayPart = [contactsArray subarrayWithRange:range]; NSDictionary *contactsDic = @{@"phone_book" : @{@"contacts" : contactsArrayPart}}; dispatch_group_enter(group); [[SSHTTPClient sharedClient] POST:@"/api/contacts" parameters:contactsDic progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { dispatch_group_leave(group); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"Failed method: %@", NSStringFromSelector(_cmd)); dispatch_group_leave(group); }]; } dispatch_group_notify(group, dispatch_get_main_queue(), ^{ [self hideSpinner]; [self loadContactsFromServer]; }); return; } |