URL Validation (Objective-C)

10,078

Solution 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.

Solution 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.

Solution 3

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

Share:
10,078
saleh Hosseinkahni
Author by

saleh Hosseinkahni

master's degree student!

Updated on July 01, 2022

Comments

  • saleh Hosseinkahni
    saleh Hosseinkahni almost 2 years

    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.