0

Is there any API or good function to format strings like "www.example.com" or just "example.com" to valid urlstrings like "http://www.example.com"?

+ (NSString*)complete:(NSString *)urlString
{
    NSArray * urlParts = [urlString componentsSeparatedByString:@"."];
    if(urlParts.count==3)
        return [NSString stringWithFormat:@"http://www.%@.%@",[urlParts objectAtIndex:1],[urlParts objectAtIndex:2]];
    else if(urlParts.count==2)
        return [NSString stringWithFormat:@"http://www.%@.%@",[urlParts objectAtIndex:0],[urlParts objectAtIndex:1]];
    return nil;
}

this is what current solution looks like, but this doesn't look very good and solid to me.

1
  • What you have currently is really bad. As it doesn't take into account many possibilities. You may want to look at using regex to check if you have a valid URL instead of componentsSeparatedByString. Currently your code would ig nore a string like thebestsiteintheworld.com/index.html which would be bad. Commented Aug 16, 2012 at 16:20

1 Answer 1

4

You can do this fairly easily with NSDataDetector:

NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:NULL];
NSString *URLString = @"www.example.com";
NSTextCheckingResult *result = [detector firstMatchInString:URLString options:0 range:NSMakeRange(0, URLString.length)];
if (result) {
    NSURL *URL = [result URL];
    NSLog(@"%@", URL); // http://www.example.com
}

You should not assume that www is a valid subdomain for any given domain btw.

If you need the result as a string, you can use the absoluteString method of NSURL, it's typically better to use NSURL instead of NSString for URLs though.

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

1 Comment

Thanks a lot, this is the kind of solution i was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.