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

时间:2015-08-07 17:58:56

标签: ios objective-c cocoa-touch nsurl

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

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

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

4 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

试试这个:

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

答案 3 :(得分:0)

试试这个。

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