我在我的应用中使用网页视图,从文本字段中获取网址。如果字符串以“http://”开头,则它可以工作。我正在尝试修改代码,以便它还可以处理用户不输入“http://”或“https://”的情况
如何检查网址中是否没有“http://”? 如何修改URL以在其中添加“http://”?
NSString *URLString = textField.text;
NSURL *URL = [NSURL URLWithString:URLString];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[self.webView loadRequest:request];
答案 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];