我是 iOS 新手
我正在尝试使用 UIWebView 制作一个简单的浏览器。
这是我的代码。
"ViewController.h"
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UITextField *addrInputField;
-(IBAction)enterButton:(id)sender;
/*go back btn*/
-(IBAction)goBackBtn:(id)sender;
/*go front btn*/
-(IBAction)goForwardBtn:(id)sender;
@end
"ViewController.m"
/*url enter button*/
-(IBAction)enterButton:(id)sender{
NSString *str = [_addrInputField text];
NSURLRequest *rqst = [NSURLRequest requestWithURL:[NSURL URLWithString:str]];
[_webView loadRequest:rqst];
}
/*go back button*/
-(IBAction)goBackBtn:(id)sender{
if([self.webView canGoBack]){
[self.webView goBack];
}
}
/*go forward button*/
-(IBAction)goForwardBtn:(id)sender{
if([self.webView canGoForward]){
[self.webView goForward];
}
}
这些简单的东西都是我的代码。
在文本字段中输入 url 并触摸 EnterButton,然后 webView 就会更改。
当我在文本字段中输入网址(如:“http://apple.com”)时, View 就会更改。
但是输入url:“apple.com”,查看不起作用。
如何在输入网址时省略协议(protocol)?
p.s 我想知道如何处理 http 和 https。
感谢阅读。
******添加详细信息。
当我按下 Enter 时..
Chrome 将我的输入“apple.com”修改为“https://apple.com”,自动添加协议(protocol)“https://”。
我想在我的应用程序中添加此功能。谢谢。
最佳答案
一旦从文本字段中获取字符串,在创建 NSURL
之后,您可以从中检索 URLScheme
。如果是nil
,可以自己添加http
。
NSURL *url = [NSURL URLWithString:str];
if url.scheme == nil {
[NSString stringWithFormat:@"http://%@",str];
url = [NSURL URLWithString:str];
}
关于ios - [iOS]如何省略协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47010320/