Add http: // to NSURL if it is not there

I am using a web view in my application, getting the url from the text box. It works if the line starts with "http: //". I am trying to change the code so that it can also handle situations where users do not enter "http: //" or "https: //"

How to check if it has the URL "http: //"? How to change the url to add "http: //" to it?

NSString *URLString = textField.text; NSURL *URL = [NSURL URLWithString:URLString]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; [self.webView loadRequest:request]; 
+6
source share
4 answers
 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]; 
+9
source

Try it.

 NSString *URLString = textField.text; if ([URLString rangeOfString:@"http://"].location == NSNotFound && [URLString rangeOfString:@"https://"].location == NSNotFound) { URLString=[NSString stringWithFormat:@"http://%@",textField.text]; } NSURL *URL = [NSURL URLWithString:URLString]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; [self.webView loadRequest:request]; 
0
source

Let me update the answer on Swift 4 and WKWebKit

  var urlString = "www.apple.com" if urlString.hasPrefix("https://") || urlString.hasPrefix("http://"){ let myURL = URL(string: urlString) let myRequest = URLRequest(url: myURL!) webView.load(myRequest) }else { let correctedURL = "http://\(urlString)" let myURL = URL(string: correctedURL) let myRequest = URLRequest(url: myURL!) webView.load(myRequest) } 
0
source

Try the following:

  NSString *URL = @"apple.com" ; NSURL *newURL ; if ([URL hasPrefix:@"http://"] || [URL hasPrefix:@"https://"]) { newURL = [NSURL URLWithString:URL] ; } else{ newURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@",URL]] ; } NSLog(@"New URL : %@",newURL) ; 
0
source

All Articles