Rox
Rox

Reputation: 909

How to check valid url?

How I can check NSURL is valid or not? 1) If I enter "facebook.com" then it should add "http://www."

2) If I enter "www.facebook.com",then it should add "http://"

3) If I enter "facebook", then It should search on google.

How I can achieve this??

I am doing this following way, but it is not working. It always return true for third case.("http://www.facebook")

if (![url.absoluteString.lowercaseString hasPrefix:@"http://"])
    {
        if(![url.absoluteString.lowercaseString hasPrefix:@"www."])
        {
            url = [NSURL URLWithString:[@"http://www." stringByAppendingString:locationField.text]];

        }
        else
        {
            url = [NSURL URLWithString:[@"http://" stringByAppendingString:locationField.text]];
        }
    }
if(![self validateUrl:url.absoluteString])
{
     url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@",[locationField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
}


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

Upvotes: 2

Views: 2750

Answers (2)

Dhiman Ranjit
Dhiman Ranjit

Reputation: 81

In swift 2,

    func verifyUrl (str: String?) -> Bool {
     //Check for nil
     var urlString = str!
     if urlString.hasPrefix("http://") || urlString.hasPrefix("https://"){

     }else{
         urlString =  "http://" + urlString
     }
     let userURL:String =  urlString

     let regex = try? NSRegularExpression(pattern: "((https|http)://)((\\w|-|m)+)(([.]|[/])((\\w|-)+))+", options: .CaseInsensitive)
     return regex?.firstMatchInString(userURL, options: [], range: NSMakeRange(0, userURL.characters.count)) != nil
   }

Upvotes: 0

kas-kad
kas-kad

Reputation: 3764

There is no need to add www. if user enter facebook.com. The http:// would be enough. Anyway the following function can eat either with or without www.

func checkURL(url: String ) -> Bool {    
    let urlRegEx = "^http(?:s)?://(?:w{3}\\.)?(?!w{3}\\.)(?:[\\p{L}a-zA-Z0-9\\-]+\\.){1,}(?:[\\p{L}a-zA-Z]{2,})/(?:\\S*)?$"
    let urlTest = NSPredicate(format: "SELF MATCHES %@", urlRegEx)
    return urlTest.evaluateWithObject(url)
}

checkURL("http://www.россия.рф/") // true
checkURL("http://www.facebook.com/") // true
checkURL("http://www.some.photography/") // true
checkURL("http://facebook.com/") // true

checkURL("http://www.россия/") // false
checkURL("http://www.facebook/") // false
checkURL("http://www.some/") // false
checkURL("http://facebook/") // false

checkURL("http://россия.рф/") // true
checkURL("http://facebook.com/") // true
checkURL("http://some.photography/") // true
checkURL("http://com/") // false

Upvotes: 5

Related Questions