Requestというクラスがあります。リクエストは非同期です。リクエストの最後に、サーバー エラーのレスポンスをチェックします。サーバー エラーが発生した場合は、通知を送信します。
+(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;
}
上記は、応答クラスの関連メソッドです。ここで、要求がサーバー エラー通知をスローするたびに、それがアプリ内のどこにあるかに関係なく、アプリがすぐにアラートを表示する必要があります。したがって、アプリケーションデリゲートにハンドラーをそのまま配置するだけでよいと考えました。
[[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];
}];
問題は、エラーが発生した場合、アプリが数分間フリーズしてからアラートが表示されることです。これはアプリケーションのライフサイクルと関係があることを理解しています。私が望むものを達成する方法はありますか (コードの単純さの観点から)、アプリが数分間フリーズしないようにする方法はありますか?これを解決する方法がわかりません。
ありがとうございました!