0

How to find out if a NSString is an website URL in Objective-c.It will be better if you provide source code. If not, tell me which class is useful is good enough.

Finally i found a way to judge,may not the best way,but useful :

    NSURL *url = [NSURL URLWithString:urlStr];
    NSURL *lazyUrlStr = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@",urlStr]];
if([[UIApplication sharedApplication] canOpenURL:url]){
            NSLog(@"it's a url");
    }else if([[UIApplication sharedApplication] canOpenURL:lazyUrlStr]){
        NSLog(@"it's a url");
    }else{NSLog(@"it isn't a url");

}

FYI: urlStr is the NSString to be judged

JJ.Yuan
  • 63
  • 12
  • @JJ.Yuan: I think it may not be a `UIString`, it'll be `NSString`. Because `UI` always refers to `UserInterface` components. – Soorej Babu May 10 '16 at 07:18
  • Possible duplicate of [Objective-C - Checking if URL exists](http://stackoverflow.com/questions/6008399/objective-c-checking-if-url-exists) – Patrick May 10 '16 at 07:18
  • 2
    i don't think so Patrick – Soorej Babu May 10 '16 at 07:19
  • 1
    duplicated question [How to quickly check if NSString object is a valid url?](http://stackoverflow.com/questions/9260779/how-to-quickly-check-if-nsstring-object-is-a-valid-url) – Mortgy May 10 '16 at 07:26
  • http://stackoverflow.com/q/8224568/653513 – Rok Jarc May 10 '16 at 07:27
  • i know i know.. but i don't want to Yuan to hate this site. He is just a beginner. Let him study – Soorej Babu May 10 '16 at 07:35
  • 1
    Possible duplicate of [How to validate an url on the iPhone](http://stackoverflow.com/questions/1471201/how-to-validate-an-url-on-the-iphone) – Tim May 10 '16 at 07:55
  • @Jeff It's not a duplicate of that question as the OP wants to know if the string is a URL to a website (i.e. http/https), not just a valid URL. – trojanfoe May 10 '16 at 12:34

1 Answers1

1

You can use URLWithString method of NSURL (if you are asking for NSString, not UIString):

NSURL *url = [NSURL URLWithString:yourUrlString];
if (url && url.scheme && url.host)
{
   //the url is ok
   NSLog(@"URL:%@", yourUrlString);
}

Hope this will help:)

Ronak Chaniyara
  • 5,335
  • 3
  • 24
  • 51