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

狂风中的少年 提交于 2019-12-19 06:28:18

问题


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

回答1:


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



回答2:


Let me update answer to 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)
    }



回答3:


Try This:

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



回答4:


Try This.

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


来源:https://stackoverflow.com/questions/31883976/add-http-to-nsurl-if-its-not-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!