总结第 1 点:在处理对服务器的所有请求的 API 类(AFHTTPSessionManager 子类)中,添加以下方法代码。API 调用 ---
- (void)getMyRecordsFromServer:(NSString *)url withLastModified:(NSTimeInterval)lastModified callbackHandler:(void (^)(id, NSError *))handler {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
self.responseSerializer = [AFHTTPResponseSerializer serializer];
[self GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
handler(responseObject, nil);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
/**********************************************************************/
NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
NSInteger statusCode = response.statusCode;
NSLog(@"Error Code=%ld",(long)statusCode);
NSLog(@"Desc=%@",response.description);
/**********************************************************************/
[self baseFailureWithError:error onFailure:handler];
}];
}
呼叫成功----
- (void)myGetRequestWithSuccess:(void (^)(id))success
onFailure:(void (^)(NSError *))failure
{
[self GET:@"api/object"
parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject)
{
// success code here.
} failure:^(NSURLSessionDataTask *task, NSError *error)
{
[[self class] baseFailureWithError:error onFailure:failure];
}];
}
之后在 baseFailureWithError:: 类方法中实现通用逻辑,然后回调您的视图控制器以实现用户特定的错误验证。失败调用----
- (void)baseFailureWithError:(NSError *)error
onFailure:(void(^)(id responseObject,NSError *error))failure
{
if (failure){
NSHTTPURLResponse *response = error.userInfo[@"AFNetworkingOperationFailingURLResponseErrorKey"];
if ([response isKindOfClass:[NSHTTPURLResponse class]] && response.statusCode == 401){
NSLog(@"Handle all 401's!");
// decide show alert or not for point 2
} else {
failure(nil, error);
}
}
}