I\'m going to show in my app a sort of UIActivityIndicatorView while parsing several JSON objects, inside a for () loop. I can\'t figure WHERE I must place the [UIActivityIndica
Solution is to
Simplify the code so that is obvious what is being done there (declaring the blocks beforehand)
Count how many requests are running and perform the global actions only when all the requests are completed.
typedef void (^AFJSONSuccessBlock) (NSURLRequest *request, NSHTTPURLResponse *response, id JSON);
typedef void (^AFJSONFailureBlock) (NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON);
[UIActivityIndicatorView startAnimating];
__block int numRequests = [arrayJSON count];
AFJSONSuccessBlock onSuccess = ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[...]
numRequests--;
if (numRequests == 0) {
[UIActivityIndicatorView stopAnimating];
}
};
AFJSONFailureBlock onFailure = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
[...]
numRequests--;
if (numRequests == 0) {
[UIActivityIndicatorView stopAnimating];
}
};
for (NSString* jsonPath in arrayJSON) {
NSString* absolutePath = [NSString stringWithFormat:@"http://WWW.REMOTESERVERWITHJSONSOURCE.NET/%@", jsonPath];
NSURL *url = [NSURL URLWithString:absolutePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:onSuccess
failure:onFailure];
[operation start];
}
Your problem is that the requests you are making in your loop are asynchronous, so your loop doesn't hang around for them to complete, it just fires off each one in quick succession and your block of code to load your arrays is executed once the data is received.
You could use a counter in your block that gets incremented every time a block finishes and then once the counter matches your [arrayJSON count]
you know when to stop the animation. Just remember to use __block
storage
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/Blocks/Articles/bxVariables.html
I would generally say that if you are unable to determine where a loop ends in your code that's an indication your code is to convoluted. Your for-loop ends just before the else statement I think. To find out you can simply click the starting bracket and XCode (if that's what you're using) will highlight the code-block...