UIWebView在ios(特別是7.x以下)開發(fā)中經(jīng)常用到的控件之一,特別是近些年H5的的迅速發(fā)展懒鉴,越來越多的原生態(tài)頁面被替換,網(wǎng)頁的加載也越發(fā)顯得重要。網(wǎng)上關(guān)于UIWebView的詳細(xì)介紹也非常多神郊,在這里僅僅是個(gè)人的一些整理,備以后之需趾唱。
1.初始化工作
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
webView.backgroundColor = [UIColor whiteColor];
webView.delegate = self;
UIWebViewDelegate中:
- (void)webViewDidStartLoad:(UIWebView *)webView;//開始加載的時(shí)候執(zhí)行
- (void)webViewDidFinishLoad:(UIWebView *)webView;//加載完成的時(shí)候執(zhí)行
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;//加載出錯(cuò)的時(shí)候執(zhí)行
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
前三個(gè)方法都很好理解涌乳,第四個(gè)方法用來實(shí)現(xiàn)一些JS交互,后面會(huì)講到
2.加載
網(wǎng)絡(luò):
NSURL *url = [NSURL URLWithString:@"http://www.reibang.com"];//http://
NSURLRequest *webReq = [NSURLRequest requestWithURL:url];
[webView loadRequest:webReq];
需要添加請(qǐng)求頭甜癞,服務(wù)端可以在這里取一些數(shù)據(jù)
NSURL *url = [NSURL URLWithString:webUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"1.0.0" forHTTPHeaderField:@"version"];
...
[webView loadRequest:request];
本地:
1.第一種方式loadRequest:
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
webView loadRequest:request];
2.第二種方式loadHTMLString:baseURL
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:html baseURL:baseURL];
3.其他
[webView goBack];//返回
[webView goForward];//向前
[webView reload];//重新加載數(shù)據(jù)
[webView stopLoading];//停止加載數(shù)據(jù)
如果我們?cè)趇OS9下直接進(jìn)行HTTP請(qǐng)求是會(huì)收到如下錯(cuò)誤提示:
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
系統(tǒng)會(huì)告訴我們不能直接使用HTTP進(jìn)行請(qǐng)求夕晓,需要在Info.plist新增一段用于控制ATS的配置: