接觸 iOS 開發一年多下來,最明顯的感受是混合式開發越來越流行。無論從成本還是速度來看,它都比傳統原生 App 開發更划算,本質上是把原生模式與網頁端結合起來。提到混合開發,Android 有 WebView 作為橋梁,iOS 這邊自然也有對應的組件——UIWebView。下面就把它的一些核心知識好好梳理一遍。
CGRect bounds = [[UIScreen mainScreen] applicationFrame]; UIWebView* webView = [[UIWebView alloc] initWithFrame:bounds];
webView.scalesPageToFit = YES; // 自動縮放頁面以適應屏幕 webView.detectsPhoneNumbers = YES; // 自動識別電話號碼,單擊可撥打
[self.view addSubview:webView];
加載網絡網頁:
NSURL* url = [NSURL URLWithString:@"https://www.baidu.com"]; NSURLRequest* request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request];
加載本地資源:
NSURL* url = [NSURL fileURLWithPath:filePath]; NSURLRequest* request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request];
此外,UIWebView 還支持把一個 NSString 對象作為源來加載。此時可以傳入一個基礎 URL,用來引導 webView 如何跟隨鏈接與加載遠程資源:
[webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"https://baidu.com"]];
UIWebView 內部會自行管理瀏覽器的導航動作,透過 goForward 與 goBack 就能控制前進後退:
[webView goBack]; [webView goForward]; [webView reload]; // 重新加載 [webView stopLoading]; // 取消加載
UIWebView 提供了一組委托方法,會在關鍵時機收到通知。使用前需先設置委托:
webView.delegate = self;
每個委托方法的第一個參數都是指向某個 UIWebView 的指針,因此同一個委托可以用於多個網頁視圖。
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType; // 當網頁視圖被指示載入內容時通知,返回 YES 才會加載。可透過 navigationType 判斷請求來源: // UIWebViewNavigationTypeLinkClicked / FormSubmitted / BackForward / Reload / FormResubmitted / Other
加載過程的監聽方法:
-(void)webViewDidStartLoad:(UIWebView*)webView; // 開始加載 -(void)webViewDidFinishLoad:(UIWebView*)webView; // 加載完成 -(void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error; // 加載出錯,會提供 NSError 標識錯誤類型
1、與 webView 交互、調用網頁中需要傳參的 JS 函數時,參數要帶單引號或雙引號(雙引號需轉義,在字符前加反斜槓);傳遞 json 字符串時則不需要加引號。
-(void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *sendJsStr = [NSString stringWithFormat:@"openFile(\"%@\")", jsDocPathStr];
[webView stringByEvaluatingJavascriptFromString:sendJsStr];
}
2、可在 shouldStartLoadWithRequest 這個代理方法中判斷與 webView 的交互,通常透過 html 裡自定義的協議來實現。
3、只有在 webView 加載完成之後,才能調用對應頁面中的 JS 方法。
4、為 webView 添加背景圖片時,記得把 opaque 設為 NO:
approvalWebView.backgroundColor = [UIColor clearColor]; approvalWebView.opaque = NO; // 是否不透明,NO 表示透明;再在其下方墊一層 imageView 展示圖片即可
5、獲取 webView 頁面內容信息:
NSString *docStr = [webView stringByEvaluatingJavascriptFromString:@"document.documentElement.textContent"]; SBJsonParser *parserJson = [[[SBJsonParser alloc] init] autorelease]; NSDictionary *contentDic = [parserJson objectWithString:docStr]; // 將 json 字符串轉為字典
6、加載本地文件的兩種常見方法:
// 方法一 NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html" inDirectory:@"mobile"]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; // 方法二 NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"]; NSString *htmlstring = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; [uiwebview loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
7、先把文件下載到本地,再用 webView 打開:
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]]; self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@", docType]]; NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]]; [attachmentData writeToFile:filePath atomically:YES]; NSURL *url = [NSURL fileURLWithPath:filePath]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [attachmentWebView loadRequest:requestObj]; // 刪除指定目錄下的文件 NSFileManager *magngerDoc = [NSFileManager defaultManager]; [magngerDoc removeItemAtPath:filePath error:nil];
8、處理 webView 展示 txt 文檔的亂碼問題,可依次嘗試不同編碼:
if ([theType isEqualToString:@".txt"]) {
// txt 分帶編碼(如 UTF-8)和不帶編碼(如 ANSI)兩種
NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr) {
aStr = [[NSString alloc] initWithData:attachmentData encoding:0x80000632]; // GBK
}
if (!aStr) {
aStr = [[NSString alloc] initWithData:attachmentData encoding:0x80000631]; // GB18030
}
NSString* responseStr = [NSString stringWithFormat:@"%@
", aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
}
9、使用 webView 加載本地或網絡文件的完整流程(參考自蘋果官方文檔 Displaying Web Content):
- (void)viewDidLoad {
[super viewDidLoad];
// 從本地加載 PDF
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];
}
// 從網絡加載
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com/"]]];
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // 顯示加載指示器
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // 隱藏加載指示器
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString* errorString = [NSString stringWithFormat:@"An error occurred: %@", error.localizedDescription];
[self.myWebView loadHTMLString:errorString baseURL:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
if ([self.myWebView loading]) {
[self.myWebView stopLoading];
}
self.myWebView.delegate = nil; // 視圖消失時斷開委托
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
10、查找 webView 內部的 scrollView:
- (void)addScrollViewListener {
UIScrollView* currentScrollView;
for (UIView* subView in self.webView.subviews) {
if ([subView isKindOfClass:[UIScrollView class]]) {
currentScrollView = (UIScrollView*)subView;
currentScrollView.delegate = self;
}
}
}
11、去掉 webView 的陰影,做成類似 scrollView 的效果:
- (void)clearBackgroundWithColor:(UIColor*)color {
self.backgroundColor = color;
for (UIView* subView in [self subviews]) {
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews]) {
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
}
12、取消長按鏈接彈出 actionSheet:
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavascriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];
}
13、攔截 webView 上的超鏈接加載:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
return NO;
} else {
return YES;
}
}
14、版本相關的坑:在 iOS 5.1 之前,用 webView 加載附件(doc、excel、ppt、pdf 等)時,必須先把附件下載到本地再加載。而剛開始加載時若退出頁面,由於 webView 內部沒有取消相關代理,會導致崩潰。此外在 iOS 5.1 上,若需要 webView 左右滑動,加載頁面時可能出現加載不全的問題,這與 webView 自身的緩存有關。
15、用 webView 做新浪微博分享時,它會自動保存登錄 cookie,可能影響分享模塊。刪除指定域 cookie 的方法:
-(void)deleteCookieForDominPathStr:(NSString *)thePath {
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
if ([[cookie domain] isEqualToString:thePath]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
}
16、在 UIWebView 中使用 flashScrollIndicators。UIWebView 內部依賴 UIScrollView,但本身沒有該方法,可以透過遍歷子視圖調用:
for (id subView in [webView subviews]) {
if ([subView respondsToSelector:@selector(flashScrollIndicators)]) {
[subView flashScrollIndicators];
}
}
17、根據內容自適應 UIWebView 的高度。有兩種方式,都需在 webViewDidFinishLoad 回調中使用。
① 使用 sizeThatFits:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
CGRect frame = webView.frame;
frame.size.height = 1; // 先設為最小高度
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
}
之所以先把高度設為 1,是因為 sizeThatFits 在當前尺寸偏大時會直接返回當前值,只有先縮到最小才能得到最合適的高度。
② 使用 JavaScript:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
CGRect frame = webView.frame;
NSString *fitHeight = [webview stringByEvaluatingJavascriptFromString:@"document.body.scrollHeight;"];
frame.size.height = [fitHeight floatValue];
webView.frame = frame;
}
總的來說,UIWebView 既能加載服務器返回的 URI,也能加載本地資源文件,還能加載服務器返回的網頁代碼,堪稱混合開發裡相當強大的一座橋梁。隨著業務越來越複雜,它出現在項目裡的頻率只會越來越高。