user717452 user717452 - 29 days ago 10
iOS Question

Showing UIAlertView at END of a For Loop...if NO errors

My following code loops through an array for Parse.com to upload from the local datastore to the server. The issue here, of course, is that it makes an UIAlertView for every successful entry...which gets annoying very quick. How can I change it so that it will still only show if no errors, but only do it one time at the end of the loop?

-(void)uploadToParse {

int i;
for (i = 0; i < [self.objects count]; i++) {
PFObject *entry = [self.objects objectAtIndex:i];


NSString *imageFileName = [entry[@"FamilyName"] stringByAppendingString:@".png"];
NSLog(@"%@", imageFileName);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageFileName];
UIImage *newImage = [UIImage imageWithContentsOfFile:filePath];
NSData* data = UIImagePNGRepresentation(newImage);


PFFile *imageFile = [PFFile fileWithName:@"Locationimage.png" data:data];

[entry setObject:imageFile forKey:@"HousePicture"];


[entry saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
if (!error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Upload Complete" message:@"Successfully added your Bible Distribution data." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];


[entry unpinInBackgroundWithName:@"Share" block:^(BOOL succeeded, NSError * _Nullable error) {

}];

}
}];


[entry unpinInBackgroundWithName:@"Share" block:^(BOOL succeeded, NSError * _Nullable error) {
[self loadObjects];
}];

}
}

Answer

I'd recommend using a dispatch_group. They allow you to queue up tasks and only after each task has completed does the completion handler get called.

This should work:

-(void)uploadToParse {

    dispatch_group_t uploadGroup = dispatch_group_create();
    int i;
    for (i = 0; i < [self.objects count]; i++) {

        dispatch_group_enter(uploadGroup);
        // ... Your code that sets up the upload task


       [entry saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
           dispatch_group_leave(uploadGroup);
        }];
    }

    dispatch_group_notify(uploadGroup, dispatch_get_main_queue(),^{
        // This gets called after each task completes.
        // Add code to show alert view here.
    });
}
Comments