URL Validation (Objective-C)

混江龙づ霸主 提交于 2019-11-30 09:14:10

问题


I am trying to validate a URL with this method:

Code:

- (BOOL) validateUrl: (NSString *) candidate {

    NSString *urlRegEx=
    @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";

    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
    return [urlTest evaluateWithObject:candidate];

}

It does not function. I think the problem is with the regular expression.


回答1:


You can use + (id)URLWithString:(NSString *)URLString method of NSURL, which returns nil if the string is malformed.

Use if (URL && URL.scheme && URL.host) for checking URL.




回答2:


Try with this..

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

it may help u out.




回答3:


NSString *urlRegEx = @"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";



回答4:


What about using the following:

NSURL * url = [NSURL URLWithString:@"http://www.google.com"];

BOOL isValid = [UIApplication.sharedApplication canOpenURL:url];

note: best practice is to use regex



来源:https://stackoverflow.com/questions/8224568/url-validation-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!