0

我正在尝试使用 if 语句检测我的请求中是否有错误theConnection。如果成功则进入第一部分,但如果有错误则不进入else。我不确定为什么。

- (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];
    }

}
4

1 回答 1

0

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

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

于 2013-04-09T15:21:47.293 回答