UIWebView 是 iOS 早期用於在應用內嵌顯示網頁內容的核心元件,即使在新版系統中已逐步被 WKWebView 取代,仍有大量老舊專案在使用它。本文以一個「校車定位」頁面為例,完整示範如何創建 UIWebView、加載遠端網頁、處理加載狀態與異常情況。
首先在類別擴展中聲明代理,並定義幾個關鍵成員變數:加載提示用的 HUD、遮罩視圖、WebView 本身,以及用於判斷環境的 IP 字串與目標網址。
@interface XiaoCheDingWeiViewController ()<UIWebViewDelegate>
{
JGProgressHUD *hud;
UIView *_hudView;
UIWebView *webView;
NSString *IPString;
NSString *string;
}
@end
在 viewDidLoad 裡,我們先手動搭建一個藍色標題列,放置「校車定位」標題與返回按鈕,接著配置 WebView 的各項屬性並加載對應網址。
- (void)viewDidLoad {
[super viewDidLoad];
//藍色頂部橫條
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
label.backgroundColor = [UIColor colorWithRed:46/255.0 green:104/255.0 blue:182/255.0 alpha:1.0];
[self.view addSubview:label];
UILabel *label0 = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 50, 10, 100, 40)];
label0.text = @"校車定位";
label0.textColor = [UIColor whiteColor];
label0.textAlignment = NSTextAlignmentCenter;
label0.backgroundColor = [UIColor clearColor];
[self.view addSubview:label0];
self.view.backgroundColor = [UIColor whiteColor];
//返回按鈕
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(10, 10, 100, 40);
[backButton addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
[backButton setTitle:@"< 返回" forState:UIControlStateNormal];
backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[self.view addSubview:backButton];
//UIWebView 預設具備快取能力,這裡主動清空快取
[[NSURLCache sharedURLCache] removeAllCachedResponses];
if (webView == nil) {
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height-50)];
}
webView.backgroundColor = [UIColor whiteColor];
webView.scalesPageToFit = YES;
webView.delegate = self;
[self GetIP];
if ([IPString isEqualToString:@"192.168.33"]) {
string = @"https://192.168.33.203:8090/3dschool/car.htm";
} else {
string = @"https://kl.scst.edu.cn:8280/3dschool/car.htm";
}
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:string]]];
[(UIScrollView *)[[webView subviews] objectAtIndex:0] setBounces:NO];
[self.view addSubview:webView];
[self showhudView];
hud = [[JGProgressHUD alloc] initWithStyle:JGProgressHUDStyleDark];
hud.textLabel.text = @"正在加載......";
}
這裡有兩個實戰細節值得注意:一是透過 removeAllCachedResponses 清除快取,避免加載到過期內容;二是根據當前設備所處的網段動態切換測試與正式伺服器位址。
下面的方法用來抓取設備的 IP,並截取前三段作為環境判斷依據。
#pragma mark - 取得當前網路 IP 位址
-(void)GetIP{
NSString *String = [NSString deviceIPAdress];
if ([String isEqualToString:@"an error occurred when obtaining ip address"]) {
//取得失敗時可在此加入處理邏輯
} else {
NSArray *IPArray = [String componentsSeparatedByString:@"."];
IPString = [NSString stringWithFormat:@"%@.%@.%@", IPArray[0], IPArray[1], IPArray[2]];
}
}
為了提升使用者體驗,我們在網頁加載期間顯示一個遮罩與 HUD 提示,加載完成或失敗後再將其移除。
- (void)showhudView
{
_hudView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height - 50)];
_hudView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_hudView];
}
//開始加載時顯示提示
- (void)webViewDidStartLoad:(UIWebView *)webView
{
[hud showInView:_hudView animated:YES];
}
//加載完成時移除遮罩
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[self RemoveHudView];
}
-(void)RemoveHudView
{
[hud dismissAnimated:YES];
if (_hudView) {
[UIView animateWithDuration:0.5 animations:^{
_hudView.alpha = 0;
} completion:^(BOOL finished) {
_hudView = nil;
}];
}
}
當加載出錯時,透過代理方法攔截錯誤資訊,並用 MBProgressHUD 向使用者顯示具體原因。
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
[self RemoveHudView];
NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
MBProgressHUD *_hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
_hud.mode = MBProgressHUDModeText;
_hud.label.text = NSLocalizedString(str, @"HUD message title");
_hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
[_hud hideAnimated:YES afterDelay:1.0];
}
- (void)goToBack{
[self.navigationController popViewControllerAnimated:YES];
}
整體來看,UIWebView 的關鍵在於 delegate 的兩個時機:開始加載與結束加載,藉此搭配 HUD 呈現流暢的等待體驗。若你在維護新專案,建議改用效能更佳、且支援更多現代網頁特性的 WKWebView。