gpt4 book ai didi

iphone - 检查与 NSURLConnection 连接的有效 IP

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:29 24 4
gpt4 key购买 nike

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

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

.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,与委托(delegate)一起使用时,在连接、连接失败和接收数据时会调用委托(delegate)方法。你应该看看 NSURLConnectionDelegate。

这是一个简单的例子:

    // In your .h

@interface MyClass : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@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

此外,只要把它扔在那里,您不一定非要使用异步调用。您可以发送不需要您实现委托(delegate)的同步调用。方法如下:

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

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

关于iphone - 检查与 NSURLConnection 连接的有效 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12608701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com