检查与NSURLConnection连接的有效IP

我目前有一个ap试图打开基于我正在与之通信的某些服务器的webview。

但是,如果iphone / ipad和服务器(或其他设备)不在同一网络上,我允许用户输入自己的服务器IP。 但是,我试图使用NSURLConnection来检测我是否可以打开与给定IP的连接,但NSURLConnection永远不会返回错误,即使服务器地址(甚至是随机url)完全是假的。

.h

@interface DetailViewController : UIViewController  { 

.m中的相关代码

  - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath { dev_ip = @"http://www.asdfasfdfa.com/"; //dev_ip = (random ip) NSMutableURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:dev_ip]]; NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (conn) { NSLog(@"Connection established"); } else{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"No Device at designated IP"] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; [alert show]; } } 

这个if / else总是输出’Connection established’。 这是不应该使用NSURLConnection的东西? 如果是这样,我可以使用什么来检测给定IP的设备以进行连接。 我需要阻止用户尝试连接到坏IP,所以最好的方法是什么?

当与委托一起使用时,NSURLConnection将在连接时调用委托方法,无法连接和接收数据。 您应该查看NSURLConnectionDelegate。

这是一个简单的例子:

  // In your .h @interface MyClass : NSObject  @end 

编辑你实际上需要两个代表。


  // In your .m @implementation MyClass - (void)myMethodToConnect { NSString *dev_ip = @"http://74.125.137.101"; // Google.com NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:dev_ip]]; NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { switch ([(NSHTTPURLResponse *)response statusCode]) { // Edited this! case 200: { NSLog(@"Received connection response!"); break; } default: { NSLog(@"Something bad happened!"); break; } } } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Error connecting. Error: %@", error); } @end 

此外,只是把它扔出去,你不一定要使用异步调用。 您可以发送同步调用,这不需要您实现委托。 就是这样:

  NSString *dev_ip = @"http://www.asdfasdfasdf.com/"; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:dev_ip]]; NSURLResponse *response = nil; NSError *error = nil; NSData *connectionData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

您可以检查响应值和错误。

有一种更好的方法来测试服务器是否有效。 Reachability类为此提供了良好的API。