在項目中有時需要加載h5,這就用到了webview
1.利用webView可加載服務器h5和本地h5
2.設置代理並遵守協議
首先需要在plist裏做一下設置
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
1.加載本地h5
UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
webView.dataDetectorTypes = UIDataDetectorTypeAll; //識別webview中的類型,例如 當webview中有電話號碼,點擊號碼就能直接打電話
webView.scrollView.scrollEnabled = NO;//禁止滑動
NSURL *url = [[NSBundle mainBundle]URLForResource:@"index" withExtension:@"html"];
或NSURL *url = [[NSBundle mainBundle] URLForResource:@"index.html"withExtension:nil];
NSURLRequest *request = [NSURLRequestre questWithURL:url];
[webView loadRequest:request];
2.加載網絡上網頁h5
UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
webView.dataDetectorTypes = UIDataDetectorTypeAll; //識別webview中的類型,例如 當webview中有電話號碼,點擊號碼就能直接打電話
webView.scrollView.scrollEnabled = NO;//禁止滑動
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request = [NSURLRequestre questWithURL:url];
[webView loadRequest:request];
3.調用的代理方法
//準備加載內容時調用,通過返回值來判斷是否設置加載
- (BOOL)webView:(UIWebView *)webViewshouldStartLoadWithRequest:(NSURLRequest *)requestnavigationType:(UIWebViewNavigationType)navigationType;
//開始加載時調用
- (void)webViewDidStartLoad:(UIWebView*)webView;
//結束加載時調用
- (void)webViewDidFinishLoad:(UIWebView*)webView;
//加載失敗時調用
- (void)webView:(UIWebView *)webViewdidFailLoadWithError:(NSError *)error;