在 iOS 應用開發中,若需於 UIWebView(或現代專案中的 WKWebView)內攔截並封鎖特定網域的載入需求,可透過實作委派模式達成。核心邏在於於導航開始前檢查請求的 URL,若符合封鎖規則則回傳 false 以取消載入。
UIWebViewDelegate 協定(Swift 專案建議改用 WKNavigationDelegate)。webView.delegate = self 設定給網頁視圖實例。webView(_:shouldStartLoadWith:navigationType:) 方法,在其中進行 URL 字串比對。@interface ViewController () <UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.webView.delegate = self;
// 載入初始頁面...
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = request.URL.absoluteString;
// 範例:封鎖所有包含 "google" 的網址
if ([urlString rangeOfString:@"google"].location != NSNotFound) {
return NO; // 取消載入
}
return YES; // 允許載入
}
@end
WKWebView 搭配 WKNavigationDelegate 的 webView(_:decidePolicyFor:decisionHandler:),效能更佳且支援非同步決策。透過委派攔截機制,即可靈活控制應用內瀏覽器的存取權限,滿足內容過濾、家長控管或企業合規等需求。