我已经检查并应用了所有可能的答案,但没有成功,因为我找不到原因。 我正在调用一个API,有时它可以正常工作,但是有时它却给我“操作无法完成(nsurlErrorDomain错误-1012)”错误。
My API calling code:
我已经创建了此全局方法来调用API。为此,我创建了一个单例课程。
-(void)getDispatchDetail:(NSString *)strDispatchId successBlock:(void(^)(NSDictionary *response))successBlock withFailureBlock:(FailureBlock)failureBlock{
NSString *urlString = [NSString stringWithFormat:@"%@%@",BASE_URL,END__POINT_getDispatchDetail];
[self MethodType:POST URL:urlString parameters:@{@"DispatchId":strDispatchId?strDispatchId:@""} withCookies:nil completionBlockWithSuccess:^(id responseObject, NSURLResponse *urlResponse) {
successBlock(responseObject);
} failure:^(NSError *error) {
[ProgressHUD dismiss];
failureBlock(error);
}];
}
-(void)MethodType:(METHOD_TYPE)methodType
URL:(NSString *)urlString
parameters:(NSDictionary *)param
withCookies:(BOOL)isCookies completionBlockWithSuccess:(void (^)(id responseObject, NSURLResponse *urlResponse))success
failure:(void (^)(NSError *error))failureRequest
{
if (isCookies){
//[ProgressHUD show:kSTRING_LOADING Interaction:NO];
}
/**
Create URl based on the Request Type
**/
NSURL *url;
switch (methodType) {
case GET:
if (param) {
NSString *strDict = [self stringFromDictionary:param];
NSString *strURL = [NSString stringWithFormat:@"%@?%@",urlString,strDict];
strURL = [strURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
url = [NSURL URLWithString:strURL];
break;
}
url = [NSURL URLWithString:urlString];
break;
case PUT:
case POST:
case DELETE:
url = [NSURL URLWithString:urlString];
break;
default:
break;
}
/**
Create Reuqest based on the Request Type
**/
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
switch (methodType) {
case GET:
[req setHTTPMethod:@"GET"];
break;
case POST:
{
[req setHTTPMethod:@"POST"];
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
failureRequest(error);
}
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:postData];
}
break;
case PUT:
{
[req setHTTPMethod:@"PUT"];
NSError *error = nil;
if (param != nil) {
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
[req setHTTPBody:postData];
}
if (error) {
failureRequest(error);
}
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}
break;
case DELETE:
{
[req setHTTPMethod:@"DELETE"];
}
break;
default:
break;
}
//self.strAccessToken = @"Token ab6520a0805b11e82c750034548b74d02464e900";
//self.strAccessToken = [ETDataModelClass getUserAccessToken];
if ([[NSUserDefaults standardUserDefaults] valueForKey:API_PARAM_USER_ACCESS_TOKEN] != nil) {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:kUserLoginTokenAndData];
NSString *tokenType = [dict objectForKey:@"token_type"];
self.strAccessToken = [NSString stringWithFormat:@"%@ %@",tokenType,[[NSUserDefaults standardUserDefaults] valueForKey:API_PARAM_USER_ACCESS_TOKEN]];
// [self.strAccessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[req setValue:self.strAccessToken forHTTPHeaderField:API_ACCESS_TOKEN];
}
NSLog(@"ReqType : %@ URL : %@, Param : %@", [self getMethodTypeName:methodType], url, param);
NSLog(@"User Token : %@",_strAccessToken);
[req setTimeoutInterval:60.0];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *responseHeader, NSData *responseBody, NSError *error)
{
NSError *errorData = nil;
NSLog(@"Response Header : %@", responseHeader);
NSLog(@"Response : %@", [[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
id responseObject1;
if(![responseBody isKindOfClass:[NSNull class]] && responseBody != nil)
responseObject1 = [NSJSONSerialization JSONObjectWithData:responseBody options:NSJSONReadingMutableLeaves error:&errorData];
else{
[ProgressHUD dismiss];
[Utility showAlertMessage:@"No Internet Connection. Make sure your device is connected to the internet." WithTitle:@""];
return ; // When response body nil we will return the control
}
// NSLog(@"Server Response ===> :\n %@", responseObject1);
// NSLog(@"Server Error ===> :\n %@", errorData);
if (error) {
if([responseObject1 isKindOfClass:[NSDictionary class]]){
if([[responseObject1 objectForKey:API_Alert_MESSAGE] isEqualToString:kAutologoutResponseFromServer]){
NSLog(@" Response ===== %@ =====", responseObject1);
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAutoLogout object:nil userInfo:responseObject1];
}
}
[ProgressHUD dismiss];
failureRequest(error);
return ;
}
else {
//[ProgressHUD dismiss];
if (!errorData) {
if (responseObject1 == nil) {
return [Utility showAlertMessage:NO_DATA_AVAILABLE WithTitle:@""];
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) responseHeader;
long statusCode = httpResponse.statusCode;
NSLog(@"statusCode : %ld",statusCode);
switch (statusCode) {
case API_STATUS_CODE_200: case API_STATUS_CODE_402:
if (success) {
success(responseObject1,responseHeader);
}
break;
case API_STATUS_CODE_500: case API_STATUS_CODE_400:
NSLog(@"responseHeader : %@",responseHeader);
NSLog(@"responseBody : %@",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
NSLog(@"error : %@",error.localizedDescription);
NSLog(@"%@",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
[Utility showAlertMessage:SERVER_ERROR WithTitle:@""];
[ProgressHUD dismiss];
break;
case API_STATUS_CODE_403:{
NSLog(@"auto logout warning : %@",responseBody);
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAutoLogout object:nil userInfo:responseObject1];
[ProgressHUD dismiss];
break;
}
default:
NSLog(@"responseHeader : %@",responseHeader);
NSLog(@"responseBody : %@",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
NSLog(@"error : %@",error.localizedDescription);
NSLog(@"%@",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
if([responseObject1 isKindOfClass:[NSDictionary class]])
if([responseObject1 valueForKey:API_Alert_MESSAGE] && [responseObject1 valueForKey:API_Alert_MESSAGE] != nil)
[Utility showAlertMessage:[responseObject1 valueForKey:API_Alert_MESSAGE] WithTitle:@""];
[ProgressHUD dismiss];
break;
}
}
else{
failureRequest(errorData);
}
}
}];
}