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

8

1 Answer 1

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:)

Sign up to request clarification or add additional context in comments.

3 Comments

Also test the value of scheme?
i use below ,is it better ? if([[UIApplication sharedApplication] canOpenURL:url]){ [[UIApplication sharedApplication] openURL:url]; }
@RonakChaniyara It is required, as your answer will be valid for a file url, which is not a reference to a website.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.