0

I am storing website addresses from users in regular NSStrings.
Some are given as "www.somewebsite.com" and some as "http://somewebsiteothersite.org".

My app should open a UIWebView and open that webpage:

    NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:[self websiteString]]];
    NSLog(@"visiting: %@",websiteString);
    [webView loadRequest:requestObj];

But what happens is that if the http:// is omitted, the UIWebView won't open the page.

Is there a descent way to build the NSURL correctly for UIWebView?

Thanks!

Ted
  • 3,805
  • 14
  • 56
  • 98

2 Answers2

1

Just add http:// if it's not there?

if (![urlStr hasPrefix:@"http://"] && ![urlStr hasPrefix:@"https://"]) {
    urlStr = [@"http://" stringByAppendingString:urlStr];
}

beware of links that are intended to not have http:// for example ftp:// or mailto:

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
0

I know Mathiass answered quicker but I want to share a similar solution

//first detect if your string has contains http:// if not add http:// to your string
    NSMutableString *websiteString = @"www.x.com";
    if ([websiteString rangeOfString:@"http://"].location == NSNotFound) {
        NSLog(@"contains http:// == false");
        websiteString = [@"http://" stringByAppendingString:websiteString];

    } else {
        NSLog(@"contains http:// == true");

    }

    NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:[self websiteString]]];
    NSLog(@"visiting: %@",websiteString);
    [webView loadRequest:requestObj];
SpaceDust__
  • 4,844
  • 4
  • 43
  • 82