Search code examples
iosobjective-ccocoa-touchnsurl

Add http:// to NSURL if it's not there


I am using web view in my app, getting a URL from a text field. It works if the string starts with "http://". I am trying to modify the code so that it can also handle the situations where users don't enter "http://" or "https://"

How to check if the URL doesn't have "http://" in it ? How to modify the URL to add "http://" in it ?

NSString *URLString = textField.text;
NSURL *URL = [NSURL URLWithString:URLString];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[self.webView loadRequest:request];

Solution

  • NSString *urlString = @"google.com";
    NSURL *webpageUrl;
    
    if ([urlString hasPrefix:@"http://"] || [urlString hasPrefix:@"https://"]) {
        webpageUrl = [NSURL URLWithString:urlString];
    } else {
        webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", urlString]];
    }
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:webpageUrl];
    [self.myWebView loadRequest:urlRequest];