混合式開發在成本與速度上優於純原生 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];
直接載入 HTML 字串(baseURL 用於決定相對路徑的解析基準):
[webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"https://baidu.com"]];
[webView goBack]; [webView goForward]; [webView reload]; [webView stopLoading];
先設定代理:
webView.delegate = self;
核心的攔截方法——每次要載入新內容前都會先經過這裡,回傳 NO 可以阻止載入:
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType;
navigationType 的可能值包含 LinkClicked、FormSubmitted、BackForward、Reload、FormResubmitted、Other。
另外三個生命週期回呼:
- (void)webViewDidStartLoad:(UIWebView *)webView; // 開始載入 - (void)webViewDidFinishLoad:(UIWebView *)webView; // 載入完成 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error; // 載入失敗
傳入的字串參數需要帶單引號或雙引號(雙引號在 Objective-C 字串中要轉義);傳 JSON 字串時則不需要額外加引號:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *sendJsStr = [NSString stringWithFormat:@"openFile(\"%@\")", jsDocPathStr];
[webView stringByEvaluatingJavaScriptFromString:sendJsStr];
}
在 shouldStartLoadWithRequest: 中判斷 URL scheme,若是我們自訂的協議就攔下來、解析參數後交給原生處理,並回傳 NO 阻止實際導航。這是 UIWebView 最主流的 JS Bridge 做法。
只有在網頁載入完成之後,才能呼叫頁面中的 JS 方法。太早呼叫會靜默失敗。
approvalWebView.backgroundColor = [UIColor clearColor]; approvalWebView.opaque = NO; // 這行很關鍵:設為透明
設定後在 webView 背後放一個 UIImageView 就能透出底圖。
NSString *docStr = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"]; SBJsonParser *parserJson = [[[SBJsonParser alloc] init] autorelease]; NSDictionary *contentDic = [parserJson objectWithString:docStr];
// 方式一
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]]];
NSString *resourceDocPath = [[[[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];
txt 有分帶編碼與不帶編碼兩種。不帶編碼的(如 ANSI 格式)可以依序嘗試不同編碼:
if ([theType isEqualToString:@".txt"])
{
NSString *aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr)
{
// 嘗試 GBK
aStr = [[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr)
{
// 再嘗試 GB18030
aStr = [[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
// 用 HTML 排版後再載入
NSString *responseStr = [NSString stringWithFormat:
@"%@
", aStr];
[attachmentWebView loadHTMLString:responseStr
baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
}
// 從本地載入
- (void)viewDidLoad
{
[super viewDidLoad];
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; // 關鍵:斷開代理避免 crash
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)addScrollViewListener
{
for (UIView *subView in self.webView.subviews)
{
if ([subView isKindOfClass:[UIScrollView class]])
{
UIScrollView *currentScrollView = (UIScrollView *)subView;
currentScrollView.delegate = self;
}
}
}
- (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];
}
}
}
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[webView stringByEvaluatingJavaScriptFromString:
@"document.documentElement.style.webkitTouchCallout = 'none';"];
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
return NO;
}
return YES;
}
iOS 5.1 之前:webView 支援 doc、excel、ppt、pdf 等格式,但附件必須先下載到本地再載入。問題是當附件剛開始載入時若使用者離開該頁面,App 會崩潰——原因是 webView 內部沒有把代理清掉。解法就是上面第 9 點提到的:在 viewWillDisappear 中把 delegate 設為 nil。
iOS 5.1:若需要讓 webView 上的頁面可左右滑動,載入時會出現頁面顯示不全的問題,這與 webView 自身的快取機制有關。
webView 會自動保存登入狀態的 cookie,做社群分享時可能因此出現非預期行為:
- (void)deleteCookieForDomainPathStr:(NSString *)thePath
{
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
if ([[cookie domain] isEqualToString:thePath])
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
}
webView 內部依賴 UIScrollView,但本身沒有 flashScrollIndicators 方法,可以往內層找:
for (id subView in [webView subviews])
{
if ([subView respondsToSelector:@selector(flashScrollIndicators)])
{
[subView flashScrollIndicators];
}
}
放在 webViewDidFinishLoad 中呼叫,可以提示使用者「這頁可以再捲」。
有時需要讓 webView 的高度剛好包住內容,不留空白也不需要捲動。兩種做法都必須在載入完成後執行。
方式一: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 從 iOS 12 起已被蘋果標記為 deprecated,App Store Connect 也不再接受僅使用 UIWebView 的新 App 或更新版本提交。新專案請改用 WKWebView。
從 UIWebView 遷移到 WKWebView 時,主要差異有幾個:
loadRequest: 改為 loadRequest:(同名但 delegate 協定不同),代理方法改為 WKNavigationDelegate。evaluateJavaScript:completionHandler:,取代 stringByEvaluatingJavaScriptFromString:。WKUserContentController 的 message handler,比攔截 URL 的做法更可靠、效能也更好。上面整理的 17 點注意事項,絕大部分概念(雙向溝通、cookie 管理、載入本地檔、進度提示)在 WKWebView 上都有對應做法,只是 API 名稱不同。
UIWebView 既能載入伺服器上的 URI,也能載入本地資源檔,還能直接渲染字串形式的 HTML,是 iOS 混合式開發最早期也是最重要的橋樑。理解它的運作方式與限制,有助於在維護老專案時少走彎路;而新專案則應直接採用 WKWebView。