NSURLConnection错误无效

时间:2013-02-21 02:44:42

标签: iphone ios nsurlconnection

我正在尝试使用theConnection上的if语句检测我的请求中是否存在错误。如果成功罚款,它会进入第一部分但如果出现错误则不会进入其他部分。我不知道为什么。

- (void)vehicleSearchRequest:(NSData *)postBodyData
{

    NSString *address = [NSString stringWithFormat:@"http://%@", serverAddress];

    //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithFormat:@"%@", address];

    NSURL *url = [NSURL URLWithString:databaseURL];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postBodyData length]];

    //SynchronousRequest to grab the data, also setting up the cachePolicy
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //if request dose not finish happen within 60 second timeout.

    // Set up request
    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:postBodyData];
    [request setTimeoutInterval:180];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (theConnection) {
        // do animation thankyou here
        NSLog(@"Sucsess!");
        [self submitSuccessful];
    } else {
        // Inform the user that the connection failed from the connection:didFailWithError method
        NSLog(@"Connectin ERROR!!!");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection error, Please try again" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [alert show];
    }

}

1 个答案:

答案 0 :(得分:0)

您的代码会检查它是否能够实例化NSURLConnection。这是一个有用的安全检查,但只有在您传递系统不支持的URL时才会失败。

连接本身是异步的,因此需要一段时间来告诉您是否存在问题。实现其委托方法以收听服务器的回复。