iPhone SDK:如何检查用户输入的IP是否有效? [英] iPhone SDK: How to check if IP entered by user is valid?

查看:59
本文介绍了iPhone SDK:如何检查用户输入的IP是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iPhone应用程序包括对服务器的几个http请求.用户可以输入服务器的IP地址,因此您可以将应用程序与自己的私有服务器结合使用.

My iPhone application includes several http requests to a server. The server's IP address can be entered by the user so you can use the app in combination with your own private server.

在发出请求之前,我总是检查输入的IP地址是否有效,并且这样做:

Before making the requests I always check whether or not the IP address entered is valid and I do it like this:

-(BOOL)urlExists {

NSString *url = [NSString stringWithFormat:@"%@", ipAddress];
NSURLRequest *myRequest1 = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
NSHTTPURLResponse* response = nil;
NSError* error = nil;
[NSURLConnection sendSynchronousRequest:myRequest1 returningResponse:&response error:&error];
if ([response statusCode] == 404){
    return NO;

}
else{
    return YES;
}

[url release];
[response release];
[error release];
[myRequest1 release];

}

只要输入的地址看起来像这样,它就可以完美工作:xx.xx.xxx.xxx 但是,如果您尝试输入"1234"或"test"之类的内容,则上面显示的代码将不起作用.因此,我必须以某种方式检查输入的地址是否看起来"像IP地址,并且我不知道该怎么做.

This works perfectly as long as the entered address looks something like this: xx.xx.xxx.xxx But if you try to enter something like this, "1234" or "test", the code shown above does not work. So I somehow have to check if the entered address "looks" like an IP-address and I have no idea how to do this.

任何建议都将不胜感激!

Any suggestions are greatly appreciated!

推荐答案

您可以通过以下方法检查网址的有效性:

You can check url validity from below method :

- (BOOL) validateUrl: (NSString *) candidate {
    NSString *urlRegEx =
    @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate];
}

这篇关于iPhone SDK:如何检查用户输入的IP是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆