@interface ViewController ()<UIWebViewDelegate> @property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem; @property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem; @property(nonatomic,weak)UIWebView * webView; - (IBAction)back; - (IBAction)forward; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //1.创建webView UIWebView * webView = [[UIWebView alloc]init]; webView.frame = self.view.bounds; self.webView = webView; [self.view addSubview:webView]; //设置代理 webView.delegate = self; //2.加载请求 //加载的三种方式,加载三种数据 //《1》加载url请求 // NSURL * url = [[NSBundle mainBundle]URLForResource:@"login" withExtension:@"html"]; // NSURLRequest * request = [NSURLRequest requestWithURL:url]; // [webView loadRequest:request]; //《2》加载html(用于显示传递过来的内容,因为loadHTMLString传递的是什么,就显示什么)(这种方式加载的网页,不能回退) // NSString * path = [[NSBundle mainBundle]pathForResource:@"login.html" ofType:nil]; // NSString * string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; // NSLog(@"----%@", string); // [webView loadHTMLString:string baseURL:nil]; //《3》加载data数据(可以加载图片,word,pdf等)(这个方法加载的也不能回退) //获取路径 NSString * path = [[NSBundle mainBundle]pathForResource:@"hell" ofType:@"pdf"]; //获取mimetype NSURL * url = [NSURL fileURLWithPath:path];//不要使用urlWithString方法 NSURLRequest * request = [NSURLRequest requestWithURL:url]; NSURLResponse * rest = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&rest error:nil];//因为需要使用这个返回值,所以使用同步方法 //加载 NSData * data = [NSData dataWithContentsOfFile:path]; [webView loadData:data MIMEType:rest.MIMEType textEncodingName:@"utf8"baseURL:nil]; NSLog(@"MIMEType-----%@",rest.MIMEType); NSLog(@"%ld",data.length); } - (IBAction)back{ [self.webView goBack];//不使用dismiss方法,因为跳转的不是控制器 } - (IBAction)forward { [self.webView goForward];//前进 } #pragma mark - UIWebViewDelegate(四个代理方法) - (void)webViewDidStartLoad:(UIWebView *)webView{ // NSLog(@"webViewDidStartLoad"); } - (void)webViewDidFinishLoad:(UIWebView *)webView{ // if ([webView canGoBack]) {//先判断这个页面有没有返回功能 // self.backItem.enabled = YES; // }else{ // self.backItem.enabled = NO; // } //简便写法 NSLog(@"########%i", [webView canGoBack]); self.backItem.enabled = [webView canGoBack]; self.forwardItem.enabled = [webView canGoForward]; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ // NSLog(@"didFailLoadWithError"); } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ //URL //"http://www.baidu.com/" //协议头://主机名//路径 //过滤掉还有baidu的url // NSString * path = request.URL.absoluteString;//注意不是URL.path这个方法,这个方法返回的是“/” // NSInteger location = [path rangeOfString:@"baidu"].location; // if (location != NSNotFound) { // return NO; // } NSLog(@"%@", request.URL.absoluteString); return YES; } @end
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/app/5101.html