您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS UIWebView 使用大全:基礎操作與 17 個實務注意事項

編輯:iOS 開發綜合

混合式開發在成本與速度上優於純原生 App,而在 Android 上擔任橋樑的是 WebView,iOS 上則是 UIWebView。以下從基礎用法一路整理到實務上常踩的坑。

一、基礎使用

1. 建立

CGRect bounds = [[UIScreen mainScreen] applicationFrame];
UIWebView *webView = [[UIWebView alloc] initWithFrame:bounds];

2. 常用屬性

webView.scalesPageToFit = YES;        // 自動縮放以適應螢幕
webView.detectsPhoneNumbers = YES;    // 自動偵測電話號碼,點擊可撥打

3. 加入畫面

[self.view addSubview:webView];

4. 載入內容

載入遠端網頁:

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"]];

5. 導航控制

[webView goBack];
[webView goForward];
[webView reload];
[webView stopLoading];

6. Delegate 代理

先設定代理:

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;  // 載入失敗

二、實務注意事項

1. 呼叫網頁 JS 函式時的引號處理

傳入的字串參數需要帶單引號或雙引號(雙引號在 Objective-C 字串中要轉義);傳 JSON 字串時則不需要額外加引號:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *sendJsStr = [NSString stringWithFormat:@"openFile(\"%@\")", jsDocPathStr];
    [webView stringByEvaluatingJavaScriptFromString:sendJsStr];
}

2. 攔截自訂協議做雙向溝通

在 shouldStartLoadWithRequest: 中判斷 URL scheme,若是我們自訂的協議就攔下來、解析參數後交給原生處理,並回傳 NO 阻止實際導航。這是 UIWebView 最主流的 JS Bridge 做法。

3. 時機問題

只有在網頁載入完成之後,才能呼叫頁面中的 JS 方法。太早呼叫會靜默失敗。

4. 讓 webView 背景透明

approvalWebView.backgroundColor = [UIColor clearColor];
approvalWebView.opaque = NO;   // 這行很關鍵:設為透明

設定後在 webView 背後放一個 UIImageView 就能透出底圖。

5. 取得頁面內容

NSString *docStr = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];
SBJsonParser *parserJson = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *contentDic = [parserJson objectWithString:docStr];

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. 先下載到本地再開啟

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];

8. 處理 txt 檔亂碼

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; }

9. 完整流程:載入本地 PDF 並處理代理

// 從本地載入
- (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; }

10. 取得內部的 scrollView

- (void)addScrollViewListener
{
    for (UIView *subView in self.webView.subviews)
    {
        if ([subView isKindOfClass:[UIScrollView class]])
        {
            UIScrollView *currentScrollView = (UIScrollView *)subView;
            currentScrollView.delegate = self;
        }
    }
}

11. 移除 webView 的陰影

- (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. 取消長按連結的選單

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [webView stringByEvaluatingJavaScriptFromString:
        @"document.documentElement.style.webkitTouchCallout = 'none';"];
}

13. 封鎖網頁內的超連結點擊

- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
    navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        return NO;
    }
    return YES;
}

14. 已知 bug

iOS 5.1 之前:webView 支援 doc、excel、ppt、pdf 等格式,但附件必須先下載到本地再載入。問題是當附件剛開始載入時若使用者離開該頁面,App 會崩潰——原因是 webView 內部沒有把代理清掉。解法就是上面第 9 點提到的:在 viewWillDisappear 中把 delegate 設為 nil。

iOS 5.1:若需要讓 webView 上的頁面可左右滑動,載入時會出現頁面顯示不全的問題,這與 webView 自身的快取機制有關。

15. 清除 cookie

webView 會自動保存登入狀態的 cookie,做社群分享時可能因此出現非預期行為:

- (void)deleteCookieForDomainPathStr:(NSString *)thePath
{
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
    {
        if ([[cookie domain] isEqualToString:thePath])
        {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
        }
    }
}

16. 手動閃示捲動標示

webView 內部依賴 UIScrollView,但本身沒有 flashScrollIndicators 方法,可以往內層找:

for (id subView in [webView subviews])
{
    if ([subView respondsToSelector:@selector(flashScrollIndicators)])
    {
        [subView flashScrollIndicators];
    }
}

放在 webViewDidFinishLoad 中呼叫,可以提示使用者「這頁可以再捲」。

17. 依內容自適應高度

有時需要讓 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 已被官方棄用

這一點必須明確說明:UIWebView 從 iOS 12 起已被蘋果標記為 deprecated,App Store Connect 也不再接受僅使用 UIWebView 的新 App 或更新版本提交。新專案請改用 WKWebView。

從 UIWebView 遷移到 WKWebView 時,主要差異有幾個:

  • 載入 API 從 loadRequest: 改為 loadRequest:(同名但 delegate 協定不同),代理方法改為 WKNavigationDelegate。
  • 執行 JavaScript 需改用 evaluateJavaScript:completionHandler:,取代 stringByEvaluatingJavaScriptFromString:。
  • JS 與原生溝通建議改用 WKUserContentController 的 message handler,比攔截 URL 的做法更可靠、效能也更好。
  • WKWebView 的網頁內容在獨立行程中執行,這也是它效能與穩定性都更好的原因,但也代表取值必須用非同步回呼。

上面整理的 17 點注意事項,絕大部分概念(雙向溝通、cookie 管理、載入本地檔、進度提示)在 WKWebView 上都有對應做法,只是 API 名稱不同。

總結

UIWebView 既能載入伺服器上的 URI,也能載入本地資源檔,還能直接渲染字串形式的 HTML,是 iOS 混合式開發最早期也是最重要的橋樑。理解它的運作方式與限制,有助於在維護老專案時少走彎路;而新專案則應直接採用 WKWebView。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved