来自服务器的错误的iOS SDK全局错误处理程序

时间:2015-12-01 14:54:32

标签: ios asynchronous error-handling afhttprequestoperation

我有一个名为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];
}];

问题是,当出现错误时,应用程序将冻结几分钟,然后显示警报。我知道这与应用程序生命周期有关。有没有办法实现我想要的(从代码简单的角度来看),并且没有让应用程序冻结几分钟?我只是不知道如何解决这个问题。

谢谢!

0 个答案:

没有答案