User-Agent(UA)標識客戶端身份。服務端常根據 UA 返回不同版本頁面(如移動端簡化版 vs PC 完整版)。iOS 原生 UIWebView/WKWebView 默認 UA 包含「iPhone」、「Safari」等標識,有時需偽裝為特定客戶端以獲取適配頁面。
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - 點擊觸發網絡請求
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"測試:當前線程 %@", [NSThread currentThread]);
// 1. 目標 URL
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
// 2. 創建可變請求(可修改 Header)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3. 關鍵:設置自定義 User-Agent
// 模擬 iPhone 正常版 UA 片段
[request setValue:@"iPhone appleWebKit" forHTTPHeaderField:@"User-Agent"];
// 4. 異步數據任務(iOS 7+ 推薦 NSURLSession)
// NSURLConnection 已在 iOS 9 棄用
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
// 5. 子線程回調:解析數據
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 6. 回主線程更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[webView loadHTMLString:html baseURL:url];
[self.view addSubview:webView];
});
}] resume]; // resume 相當於啟動連接
}
@end
NSURLSession(iOS 7+):現代網絡 API,支持後台下載、斷點續傳、代理協議豐富,**默認異步**,無同步方法。NSURLConnection:舊 API,iOS 9 起棄用,不再維護。默認在後台線程(非主隊列)。任何 UI 操作(如創建 WebView、添加子視圖)必須派發到主隊列:
dispatch_async(dispatch_get_main_queue(), ^{ /* UI 代碼 */ });
真實 iPhone Safari UA 示例:
Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)
AppleWebKit/605.1.15 (KHTML, like Gecko)
Version/15.0 Mobile/15E148 Safari/604.1
示例中簡化為 iPhone appleWebKit 僅為演示;生產環境建議完整模擬目標客戶端 UA,避免服務端邏輯判斷失效。
UIWebView 自 iOS 12 起棄用,App Store 審核可能拒絕。新項目請使用 WKWebView(需導入 WebKit.framework)。
#import
@property (nonatomic, strong) WKWebView *webView;
- (void)loadWithCustomUA {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
[self.view addSubview:self.webView];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"自定義 UA 字符串" forHTTPHeaderField:@"User-Agent"];
[self.webView loadRequest:request];
}
NSMutableURLRequest 修改 User-Agent Header。NSURLSession 異步請求,回調在子線程,UI 回主線程。UIWebView,改用 WKWebView。