我在应用程序中使用AFNetworking,然后执行以下POST代码 一切都很好(请求成功与服务器通信),但是当我在一个特定的动作上调用这个方法时,它会传递特定的参数(一个小的NSDictionary,有4个键和值),并且只有这个动作,我才会失败8次阻挡8次,很少我获得成功阻止。 问题变得更加棘手,因为即使我得到了故障块,服务器也会获得传递的参数。
为什么会这样?
+ (void)postToServerWithParameters:(NSDictionary *)parameters
andPostPath:(ServerOperation)operation
andCallback:(serverResponse)callback
{
if (retryTimes <= 0) {
callback(0, 0, @"error in posting, number of retries is finished", nil);
retryTimes = 3;
return;
}
NSString *postPath = [self choosePostPathByServerOperation:operation];
NSURL *url = [NSURL URLWithString:BASE_URL];
NSLog(@"parameters recieved:\n %@", parameters);
NSLog(@"base url to post:\n %@", url.absoluteString);
[clientRequest setObject:parameters];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setParameterEncoding:AFJSONParameterEncoding];
[client setDefaultHeader:@"Accept" value:@"application/json"];
[client postPath:postPath
parameters:[clientRequest dictionaryWithValuesForKeys:nil]
success:^(AFHTTPRequestOperation *innerOperation, id responseObject) {
// init the retry counter
retryTimes = 3;
NSLog(@"post path: %@ response from AFNetworking: %@",postPath, responseObject);
int errorCode = [responseObject[@"mCode"] intValue];
BOOL isValidToken = [responseObject[@"mIsValidtoken"] boolValue];
NSString *msg = responseObject[@"mMessage"];
id object = responseObject[@"mData"];
// and if the callback is not nil,
// will will send the data to it.
if (callback) {
callback(errorCode, isValidToken, msg, object);
}
}
failure:^(AFHTTPRequestOperation *innerOperation, NSError *error) {
NSLog(@"AFclient:%@", client);
NSLog(@"request faild with AFNetworking\nerror: %@", error);
// handle comunication error with retries (till 3)
retryTimes--;
[self postToServerWithParameters:parameters andPostPath:operation andCallback:callback];
}
];
}
错误是:
error: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x13423a80 {NSErrorFailingURLStringKey=http://www.some.url.com/something, NSErrorFailingURLKey=http://www.some.url.com/something, NSLocalizedDescription=The network connection was lost., NSUnderlyingError=0xb9a7030 "The network connection was lost."}
解决
问题出在服务器端。执行特定POST时,服务器在后台线程中执行了一个引发异常的操作。这解释了为什么POST成功并随机失败。