UIWebView的使用
@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
</pre>