I have a class called Request. A request is asynchronous. At the end of the request, I check the response for a server error. If there is a server error, I send out a notification.
+(BOOL)checkForResponseError:(NSArray*)response{
if ([[response objectAtIndex:1] boolValue] == YES) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"Server Error" object:nil userInfo:@{@"error":response[0]}];
NSLog(@"Server Response Error %@", response[0]);
return YES;
//[NSException raise:@"Server error on response" format:@"Response error: %@", response[0]];
}else if(response == nil){
NSLog(@"nil response");
#ifdef DEBUG
[NSException raise:@"Error 500" format:@"Check the logs for more information"];
#endif
return YES;
}
return NO;
}
+(Request*)request{
Request *request = [[Request alloc] init];
request.success = ^(AFHTTPRequestOperation *operation, id responseObj) {
NSLog(@"Success on operation %@ with result %@", [operation.request.URL absoluteString], operation.responseString);
NSArray *result = responseObj;
if (![Request checkForResponseError:result]){
request.completion(result);
}
};
request.failure = ^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Error: %@, result %@", error.localizedDescription, operation.responseString);
#ifdef DEBUG
[NSException raise:@"action failed" format:@"Link %@ Failed with objective c error: %@", [operation.request.URL absoluteString], error];
#endif
};
return request;
}
-(AFHTTPRequestOperationManager*)getWithAction:(NSString *)action parameters:(NSDictionary*)params success:(void (^)(NSArray*))c{
NSLog(@"Getting with action %@ and params %@", action, params);
completion = c;
AFHTTPRequestOperationManager *manager = [Header requestOperationManager];
[manager GET:[NSString stringWithFormat:@"%@%@", BASE_URL, action] parameters:params success:success failure:failure];
return manager;
}
The above are the relevant methods in the response class. Now- whenever the request throws up a Server Error notification, no matter where it is in the app, I need the app to show an alert immediately. So I thought to simply put a handler in the application delegate as such:
[[NSNotificationCenter defaultCenter] addObserverForName:@"Server Error" object:nil queue:nil usingBlock:^(NSNotification* notif){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[notif userInfo][@"error"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}];
Problem is, that when there is an error, the app will freeze for a few minutes and then show the alert. I understand this has something to do with the application lifecycle. Is there a way to achieve what I want (from a code simplicity standpoint), and not have the app freeze for a few minutes?I just don't have any idea how to solve this.
Thank you!