如果NSURL不存在,请将http://添加到NSURL [英] Add http:// to NSURL if it's not there
本文介绍了如果NSURL不存在,请将http://添加到NSURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的应用中使用网页视图,从文本字段中获取网址。如果字符串以http://开头,则它可以工作。我正在尝试修改代码,以便它还可以处理用户不输入http://或https://的情况
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://"
如何检查URL中是否没有http://?
如何修改URL以在其中添加http://?
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];
推荐答案
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];
这篇关于如果NSURL不存在,请将http://添加到NSURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文