很多 App 需要在內部打開網頁——查看使用條款、閱讀說明文件、載入動態內容。UIWebView 自帶了前進、後退、重新載入、停止載入等能力,只要正確包裝,就能做出一個功能完整的內嵌瀏覽器。
導航相關的方法:
- (void)reload;
- (void)stopLoading;
- (void)goBack;
- (void)goForward;
對應的唯讀狀態屬性,用來判斷按鈕是否該啟用:
@property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
@property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
@property(nonatomic, readonly, getter=isLoading) BOOL loading;
載入內容的三種入口:
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- (void)loadData:(NSData *)data
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)textEncodingName
baseURL:(NSURL *)baseURL;
載入網路請求的最小範例:
NSURL *url = [NSURL URLWithString:@"https://www.google.com.hk"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
首頁放一個 UIButton 與一個 UITextField,分別用來觸發跳轉與輸入網址。接著新增一個 BrowserController 負責承載 UIWebView。
// 瀏覽器本體
UIWebView *webView;
// 功能欄
UIView *toolBar;
// 功能按鈕
UIButton *stopButton; // 停止載入
UIButton *previousButton; // 後退
UIButton *nextButton; // 前進
UIButton *reloadButton; // 重新載入
// 目前網址
NSURL *_currenURL;
// 螢幕寬度
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
// 螢幕高度
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
// 導航欄高度
#define NAVIGATION_BAR_HEIGHT 44.0f
// 狀態欄高度
#define STATUS_BAR_HEIGHT 20.0f
// 工具欄高度
#define TOOL_BAR_HEIGHT 30
// 載入請求
- (void)loadUrl:(NSString *)url;
- (void)loadURLof:(NSURL *)url;
// 初始化功能欄
- (void)loadToolBar;
// 更新功能欄按鈕狀態
- (void)reflashButtonState;
// 建立等待視圖
- (void)createLoadingView;
// 更新等待視圖
- (void)freshLoadingView:(BOOL)b;
不使用 xib 時,重寫 -loadView 來建立 view hierarchy:
- (void)loadView
{
[super loadView];
if (webView == nil) {
webView = [[UIWebView alloc] initWithFrame:CGRectMake(
0.0, 0.0,
SCREEN_WIDTH,
SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT - TOOL_BAR_HEIGHT)];
webView.delegate = self;
webView.scalesPageToFit = YES;
[self.view addSubview:webView];
}
if (!toolBar) {
[self loadToolBar];
}
}
/**
* 建立底部功能欄
*/
- (void)loadToolBar
{
float toolY = self.view.frame.size.height - TOOL_BAR_HEIGHT - 44 - 20;
toolBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, toolY, 320.0, TOOL_BAR_HEIGHT)];
toolBar.backgroundColor = [UIColor orangeColor];
UIImage *stopImg = [UIImage imageNamed:@"stopButton.png"];
UIImage *nextImg = [UIImage imageNamed:@"nextButtonWeb.png"];
UIImage *previousImg = [UIImage imageNamed:@"previousButton.png"];
UIImage *reloadImg = [UIImage imageNamed:@"reloadButton.png"];
stopButton = [[UIButton alloc] initWithFrame:CGRectMake(44.0, 3.0, 24.0, 24.0)];
[stopButton setImage:stopImg forState:UIControlStateNormal];
[stopButton addTarget:self action:@selector(stopWebView:)
forControlEvents:UIControlEventTouchUpInside];
previousButton = [[UIButton alloc] initWithFrame:CGRectMake(112.0, 3.0, 24.0, 24.0)];
[previousButton setImage:previousImg forState:UIControlStateNormal];
[previousButton addTarget:self action:@selector(back:)
forControlEvents:UIControlEventTouchUpInside];
nextButton = [[UIButton alloc] initWithFrame:CGRectMake(180.0, 3.0, 24.0, 24.0)];
[nextButton setImage:nextImg forState:UIControlStateNormal];
[nextButton addTarget:self action:@selector(forward:)
forControlEvents:UIControlEventTouchUpInside];
reloadButton = [[UIButton alloc] initWithFrame:CGRectMake(248.0, 3.0, 24.0, 24.0)];
[reloadButton setImage:reloadImg forState:UIControlStateNormal];
[reloadButton addTarget:self action:@selector(reload:)
forControlEvents:UIControlEventTouchUpInside];
[toolBar addSubview:stopButton];
[toolBar addSubview:previousButton];
[toolBar addSubview:nextButton];
[toolBar addSubview:reloadButton];
[self.view addSubview:toolBar];
}
#pragma mark - webView actions
- (void)back:(id)sender
{
if (webView.canGoBack) {
[webView goBack];
}
}
- (void)reload:(id)sender
{
[webView reload];
[self freshLoadingView:YES];
}
- (void)forward:(id)sender
{
if (webView.canGoForward) {
[webView goForward];
}
}
- (void)stopWebView:(id)sender
{
[webView stopLoading];
}
- (void)loadUrl:(NSString *)url
{
if (webView) {
// 還原被過度轉義的 & 字元
url = [url stringByReplacingOccurrencesOfString:@"%26" withString:@"&"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[webView loadRequest:request];
}
}
- (void)loadURLof:(NSURL *)url
{
self.currenURL = url;
}
// 依 canGoBack / canGoForward 啟用或停用按鈕
- (void)reflashButtonState
{
previousButton.enabled = webView.canGoBack;
nextButton.enabled = webView.canGoForward;
}
- (void)createLoadingView
{
UIView *v = [UIApplication sharedApplication].keyWindow;
hub = [[MBProgressHUD alloc] initWithView:v];
hub.delegate = self;
hub.removeFromSuperViewOnHide = YES;
hub.labelText = @"加載中...";
[v addSubview:hub];
// 注意:hub 的 frame 必須與要附加它的 view 一致,否則容易出問題
}
- (void)freshLoadingView:(BOOL)b
{
if (b) {
[hub show:YES];
[hub hide:YES afterDelay:3];
} else {
[hub hide:YES];
}
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
[self reflashButtonState];
[self freshLoadingView:YES];
self.currenURL = [request URL];
return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[self reflashButtonState];
[self freshLoadingView:NO];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[self reflashButtonState];
[self freshLoadingView:NO];
}
UIWebView 已被蘋果標記為不建議使用,新專案應改用 WKWebView。移轉時主要對應如下:
-loadRequest: 名稱不變,但建議改用 -loadHTMLString:baseURL: 或 load(_:mimeType:characterEncodingName:baseURL:) 的 WK 版本reload、stopLoading 相同goBack/goForward 相同,狀態改查 canGoBack/canGoForward(屬性名稱一致)WKNavigationDelegate,方法名為 decidePolicyFor navigationAction、didFinish navigation、didFail navigation,且需要加入 WKUIDelegate 才能處理 alert 等互動WKUserContentController 的 add(_:name:) 與 evaluateJavaScript(_:completionHandler:)另外,WKWebView 的 scalesPageToFit 相當於 WKWebViewConfiguration 中的 viewportMeta 相關設定,需另行處理。