3

私の iPhone アプリケーションには、サーバーへのいくつかの http 要求が含まれています。サーバーのIPアドレスはユーザーが入力できるため、独自のプライベートサーバーと組み合わせてアプリを使用できます.

リクエストを行う前に、入力された IP アドレスが有効かどうかを常に確認し、次のようにします。

-(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 アドレスのように「見える」かどうかを何らかの方法で確認する必要があり、これを行う方法がわかりません。

どんな提案でも大歓迎です!

4

2 に答える 2

8

以下のメソッドから URL の有効性を確認できます。

- (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];
}
于 2011-03-01T12:45:37.183 に答える
2
-(BOOL)isIPAddressValid:(NSString*)ipAddress{

ipAddress = [ipAddress stringByReplacingOccurrencesOfString:@"https://" withString:@""];
ipAddress = [ipAddress stringByReplacingOccurrencesOfString:@"http://" withString:@""];

NSArray *components = [ipAddress componentsSeparatedByString:@"."];
if (components.count != 4) {
    return NO;
}
NSCharacterSet *unwantedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
if ([ipAddress rangeOfCharacterFromSet:unwantedCharacters].location != NSNotFound){
    return NO;
}
for (NSString *string in components) {
    if ((string.length < 1) || (string.length > 3 )) {
        return NO;
    }
    if (string.intValue > 255) {
        return NO;
    }
}
if  ([[components objectAtIndex:0]intValue]==0){
    return NO;
}
return YES;

}

于 2016-01-18T09:00:04.947 に答える