我目前有一个应用程序,它尝试根据我正在与之通信的某些服务器打开网络视图。
但是,我允许用户输入自己的服务器 IP,以防 iphone/ipad 和服务器(或其他设备)不在同一网络上。但是,我尝试使用 NSURLConnection 来检测是否可以打开与给定 IP 的连接,但 NSURLConnection 永远不会返回错误,即使服务器地址(甚至随机网址)完全是伪造的。
the .h
@interface DetailViewController : UIViewController <UIPopoverControllerDelegate, UISplitViewControllerDelegate, UITableViewDataSource, UITableViewDelegate,UIWebViewDelegate, NSURLConnectionDataDelegate> {
.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 始终输出“已建立连接”。这是 NSURLConnection 不应该用来做的事情吗?如果是这样,我可以使用什么来检测给定 IP 上的设备进行连接。我需要阻止用户尝试连接到错误的 IP,那么最好的方法是什么?
NSURLConnection 与委托一起使用时,在连接、连接失败和接收数据时都会调用委托方法。您应该查看 NSURLConnectionDelegate。
这是一个简单的例子:
// In your .h
@interface MyClass : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
@end
EDIT您实际上需要两名代表。
// 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];
您可以检查响应值和错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)