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

后端 未结 5 1159
粉色の甜心
粉色の甜心 2021-01-11 22:50

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

相关标签:
5条回答
  • 2021-01-11 23:04

    I solved like this, Swift 4 and up:

    var yourString = "facebook.com"
    var urlPath = ""
    if yourString.contains(find: "https://") {
       urlPath = path
    } else {
       let newPath = "https://\(path)"
       urlPath = newPath
    }
    
    guard let url = URL(string: urlPath) else {return}
    UIApplication.shared.open(url)
    
    0 讨论(0)
  • 2021-01-11 23:06

    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];
    
    0 讨论(0)
  • 2021-01-11 23:07

    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) ;
    
    0 讨论(0)
  • 2021-01-11 23:16
    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];
    
    0 讨论(0)
  • 2021-01-11 23:23

    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)
        }
    
    0 讨论(0)
提交回复
热议问题