我正在学习WebView。
当我做类似的事情
NSString *url = @"www.google.com";
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
它失败。
但是,当我www.google.com
在标准浏览器中输入(或什至是google.com)时,它就可以正常工作。
我还注意到,加载页面后,标准浏览器中的url文本字段会将链接从更改www.google.com
为https:// www. google.co.in/?gws_rd=ssl
在上面的代码中,当我设置NSString *url = @"https://www.google.co.in/?gws_rd=ssl"
它工作正常时
那么,我该如何实现我的WebView视图,以便如果它可以像标准浏览器一样工作,那么它就属于上述上下文
UIWebView
在开始请求时始终需要http或https,如果您单击webView内的链接,它将自行处理。所以这是如何处理它:
- (void)viewDidLoad
{
[super viewDidLoad];
UITextField *addressBar = [[UITextField alloc] init];
[addressBar setDelegate:self];
[self loadRequestFromString:@"www.google.com"];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self loadRequestFromString:textField.text];
[textField resignFirstResponder];
return YES;
}
- (void)loadRequestFromString:(NSString *)urlString
{
NSURL *webpageUrl;
if ([urlString hasPrefix:@"http://"] || [urlString hasPrefix:@"https://"]) {
webpageUrl = [NSURL URLWithString:urlString];
} else if ([urlString containsString:@" "] || ![urlString containsString:@"."]) {
webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
} else {
webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", urlString]];
}
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:webpageUrl];
[_webView loadRequest:urlRequest];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句