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

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

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

试试这个

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及以上:

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)

相关内容

最新更新