如果NSURL不存在,请将http://添加到NSURL

我在我的应用程序中使用Web视图,从文本字段中获取URL。 如果字符串以“http://”开头,则它可以工作。 我正在尝试修改代码,以便它还可以处理用户不输入“http://”或“https://”的情况

如何检查URL中是否没有“http://”? 如何修改URL以在其中添加“http://”?

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

 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]; 

尝试这个。

 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]; 

让我更新Swift 4和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) } 

尝试这个:

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