如何检查Objective c中是否没有服务器响应

时间:2015-09-08 08:03:02

标签: ios iphone json server nsurlconnection

我正在尝试点击网络服务。一切都很好。但如果服务器不工作,那么我的应用程序崩溃了。 如何处理NO SERVER RESPONSE。 请帮忙

以下是我点击网络服务的代码。

NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:@"0" forKey:@"unit"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:get options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:@"req=%@",jsonInputString];

NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@",getCommunity]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (responseData != nil) {
    NSDictionary *jsonRecieveDict = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSLog(@"jsonArray  =======%@",jsonRecieveDict);
 }
if (error)
{
    UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"Servor not responding" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [errorAlert show];
}

**错误是因为来自服务器的无效状态代码**

1 个答案:

答案 0 :(得分:3)

if (error != nil) {
    // Something went wrong...
    NSLog(@"Servor not responding %@",error.description);
    return;
}
if ([response statusCode] >= 300) {
    NSLog(@"Servor not responding, status code: %ld", (long)[response statusCode]);
    return;
}

第一个条件应该是错误检查,第二个是如果响应来检查状态代码然后只执行剩余的操作

同时将NSURLResponse *response;更改为NSHTTPURLResponse *response

或差异实施

NSMutableDictionary *get = [[NSMutableDictionary alloc]init];
[get setObject:@"0" forKey:@"unit"]; 

if([NSJSONSerialization isValidJSONObject:get]){


//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:nil];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"your url"]];


[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonData];


NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *session=[NSURLSession sessionWithConfiguration:config];

NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if(response){
        NSString *resp = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
        NSLog(@"Echo %@",resp);


    }

    else{
        NSLog(@"Timeout");

    }



}];
[task resume];


}