本文系Smallfan(程序猿小風(fēng)扇)原創(chuàng)內(nèi)容,轉(zhuǎn)載請(qǐng)?jiān)谖恼麻_頭顯眼處注明作者和出處。
背景
筆者在《WKWebView》一文中提到過,WKWebView 在獨(dú)立于 app 進(jìn)程之外的進(jìn)程中執(zhí)行網(wǎng)絡(luò)請(qǐng)求,請(qǐng)求數(shù)據(jù)不經(jīng)過主進(jìn)程,因此,在 WKWebView 上直接使用 NSURLProtocol 無法攔截請(qǐng)求。所以如果需要使用到攔截請(qǐng)求,有種可行地方案是使用蘋果開源的 Webkit2 源碼暴露的私有API(詳見原文第3小節(jié):NSURLProtocol問題)。
但使用私有API,必然帶來以下幾個(gè)問題:
- 審核風(fēng)險(xiǎn)
- 攔截http/https時(shí),post請(qǐng)求body丟失
- 如使用ajax hook方式,可能存在 post header字符長(zhǎng)度限制 、Put類型請(qǐng)求異常 等
由此看來,在 iOS11 WKURLSchemeHandler [探究] 到來之前,私有API并不那么完美。
所幸通過尋找發(fā)現(xiàn),iOS系統(tǒng)上具備搭建服務(wù)器能力,理論上對(duì)實(shí)現(xiàn) WKWebView 離線資源加載 存在可能性。
分析
基于iOS的local web server,目前大致有以下幾種較為完善的框架:
- CocoaHttpServer (支持iOS、macOS及多種網(wǎng)絡(luò)場(chǎng)景)
- GCDWebServer (基于iOS,不支持 https 及 webSocket)
- Telegraph (Swift實(shí)現(xiàn),功能較上面兩類更完善)
因?yàn)槟壳按蟛糠諥PP已經(jīng)支持ATS,且國(guó)內(nèi)大部分項(xiàng)目代碼仍采用OC實(shí)現(xiàn),故本文將以 CocoaHttpSever 為基礎(chǔ)進(jìn)行實(shí)驗(yàn)。
Telegraph 是為補(bǔ)充 CocoaHttpSever 及 GCDWebServer 不足而誕生,對(duì)于純Swift項(xiàng)目,推薦使用 Telegraph 。
初出茅驢
在 project工程文件 中引入 CocoaHttpServer 之后,
- 首先實(shí)現(xiàn)一個(gè)服務(wù)管理。
#import "LocalWebServerManager.h"
#import "HTTPServer.h"
#import "MyHTTPConnection.h"
@interface LocalWebServerManager ()
{
HTTPServer *_httpServer;
}
@end
@implementation LocalWebServerManager
+ (instancetype)sharedInstance {
static LocalWebServerManager *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[LocalWebServerManager alloc] init];
});
return _sharedInstance;
}
- (void)start {
_port = 60000;
if (!_httpServer) {
_httpServer = [[HTTPServer alloc] init];
[_httpServer setType:@"_http._tcp."];
[_httpServer setPort:_port];
NSString * webLocalPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Resource"];
[_httpServer setDocumentRoot:webLocalPath];
NSLog(@"Setting document root: %@", webLocalPath);
}
if (_httpServer && ![_httpServer isRunning]) {
NSError *error;
if([_httpServer start:&error]) {
NSLog(@"start server success in port %d %@", [_httpServer listeningPort], [_httpServer publishedName]);
} else {
NSLog(@"啟動(dòng)失敗");
}
}
}
- (void)stop {
if (_httpServer && [_httpServer isRunning]) {
[_httpServer stop];
}
}
@end
- 然后選擇其啟動(dòng)時(shí)機(jī),一般選擇在
AppDelegate中或WKWebView請(qǐng)求之前。
- (void)viewDidLoad {
[super viewDidLoad];
//Setup WKWebView
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];
configuration.userContentController = controller;
configuration.processPool = [[WKProcessPool alloc] init];
_wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds
configuration:configuration];
_wkWebView.navigationDelegate = self;
_wkWebView.UIDelegate = self;
[self.view addSubview:_wkWebView];
//Start local web server
[[LocalWebServerManager sharedInstance] start];
//Local request which use local resource
[self loadLocalRequest];
//Remote request which use local resource
// [self loadRemoteRequest];
}
- 在 project工程 中引入相對(duì)資源目錄(藍(lán)色文件夾),在該目錄中實(shí)現(xiàn)一個(gè)
index.html和hi.js資源文件
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello</title>
<script type="text/javascript" src="http://localhost:60000/hi.js"></script>
</head>
<body bgcolor="#4F8FFF">
<center>
<h1><br><br><br><br><br><br>恭喜你 服務(wù)器運(yùn)行成功!</h1>
<h5><br>點(diǎn)擊下面按鈕試一下</h5>
<input type='button' value='調(diào)用本地js資源中的方法' onclick='invokeAlert()'/>
</center>
</body>
</html>
function invokeAlert() {
alert('Perfect!')
}
- 通過WKWebView訪問
http://localhost:60000/index.html即可。
通過以上4步,即可開啟iOS本地http服務(wù),通過WKWebView訪問本地的html資源。
不過本文目的是 “基于LocalWebServer實(shí)現(xiàn)WKWebView離線資源加載”,所謂離線資源加載,指的是:頁面資源在遠(yuǎn)端服務(wù)器,而頁面中的部分資源在iOS本地沙盒中。
放在上面的例子上,也就是 index.html 應(yīng)該在遠(yuǎn)程的 nginx 或 apache 等服務(wù)上運(yùn)行,而 hi.js 應(yīng)該存放在APP的資源目錄之中。
此舉是否可行呢?我們?cè)囋嚳础?br>
將 index.html 改名為 demo.html 配置在 http://smallfan.net 中,直接進(jìn)行訪問
- (void)loadRemoteRequest {
if (_wkWebView) {
[_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://smallfan.net/demo.html"]]];
}
}
實(shí)驗(yàn)結(jié)果:可行。
也就是說,通過以下該方式實(shí)現(xiàn):HTML頁面內(nèi)資源允許請(qǐng)求本地服務(wù)器。
<script type="text/javascript" src="http://localhost:60000/hi.js"></script>
支持https
正如前面所提:支持ATS已經(jīng)成為一個(gè)正確而有效的選擇。
在
Safari及Apple WebKit中:在https頁面內(nèi),不允許http請(qǐng)求存在,否則一概會(huì)被block。
因此如果已經(jīng)支持了https,那么頁面中的 http://localhost:60000/hi.js 也必須 支持https才行。問題是,頁面https我們可以采用CA頒發(fā)的合法證書進(jìn)行雙向或單向認(rèn)證,而localhost并不是一個(gè)合法的host,也就是說我們需要為它實(shí)現(xiàn)一個(gè)自簽名證書。
1. 實(shí)現(xiàn)local server自簽名證書
因?yàn)閕OS開發(fā)使用MacOS,以下行為默認(rèn)系統(tǒng)已經(jīng)安裝OpenSSL。
首先到 OpenSSL官網(wǎng) 下載最新版本,解壓后在app目錄中找到CA.sh,拷貝到根目錄,然后運(yùn)行
% sh ~/CA.sh -newca
運(yùn)行完后會(huì)生成一個(gè)demoCA的目錄,里面存放了CA的證書和私鑰,同時(shí)記住自己設(shè)置的授權(quán)密碼。
創(chuàng)建一個(gè)目錄
% mkdir server
然后創(chuàng)建一個(gè)私鑰
% openssl genrsa -out server/server-key.pem 2048
創(chuàng)建證書請(qǐng)求
% openssl req -new -out server/server-req.csr -key server/server-key.pem
此時(shí)終端會(huì)要求你填寫地區(qū)、姓名等信息,Common Name 這一項(xiàng)必須填 localhost 或者 127.0.0.1 ,如果填寫127.0.0.1,那么頁面中請(qǐng)求只能使用https://127.0.0.1:60000 而不能使用 https://localhost:60000,反之相同。
自簽署證書
% openssl x509 -req -in server/server-req.csr -out server/server-cert.pem -signkey server/server-key.pem -CA demoCA/cacert.pem -CAkey demoCA/private/cakey.pem -CAcreateserial -days 3650
將證書導(dǎo)出成瀏覽器支持的.p12格式,記得導(dǎo)出密碼(本文為: b123456)
% openssl pkcs12 -export -clcerts -in server/server-cert.pem -inkey server/server-key.pem -out server/server.p12
自此,自簽名證書生成完成。
2. 配置自簽名證書
將p12文件導(dǎo)入 project工程 中的資源目錄中,
同時(shí)新建一個(gè) MyHttpConnection 繼承于 HttpConnection ,重載 - (BOOL)isSecureServer 方法及 sslIdentityAndCertificates 方法。
#import "MyHTTPConnection.h"
@implementation MyHTTPConnection
- (BOOL)isSecureServer {
return YES;
}
- (NSArray *)sslIdentityAndCertificates {
SecIdentityRef identityRef = NULL;
SecCertificateRef certificateRef = NULL;
SecTrustRef trustRef = NULL;
//p12文件資源路徑
NSString *thePath = [[NSBundle bundleWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Resource"]] pathForResource:@"localhost" ofType:@"p12"];
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
//p12文件導(dǎo)出密碼
CFStringRef password = CFSTR("b123456");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = errSecSuccess;
securityError = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items);
if (securityError == 0) {
CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemIdentity);
identityRef = (SecIdentityRef)tempIdentity;
const void *tempTrust = NULL;
tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);
trustRef = (SecTrustRef)tempTrust;
} else {
NSLog(@"Failed with error code %d",(int)securityError);
return nil;
}
SecIdentityCopyCertificate(identityRef, &certificateRef);
NSArray *result = [[NSArray alloc] initWithObjects:(__bridge id)identityRef, (__bridge id)certificateRef, nil];
return result;
}
@end
將 HTTPConnetion.m 的 startConnection 方法中
[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString *)kCFStreamSSLLevel];
替換為
[settings setObject:@"2" forKey:GCDAsyncSocketSSLProtocolVersionMin];
[settings setObject:@"2" forKey:GCDAsyncSocketSSLProtocolVersionMax];
同時(shí)在啟動(dòng) HTTPServer(調(diào)用 startServer )之前,使用 setConnectionClass 方法將 HTTPConnecdtion 替換為 MyHTTPConnection
[_httpServer setConnectionClass:[MyHTTPConnection class]];
自此,https服務(wù)配置完成。
3. WKWebView證書配置
對(duì)于自簽名證書,WKWebView需要在WKNavagationDelegate方法中允許使用:
- (void)webView:(WKWebView *)webView
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, card);
}
}
4. ATS設(shè)置
在 Info.plist 中,找到 App Transport Security Settings 項(xiàng),在其中增加一項(xiàng) Allow Arbitrary Loads in Web Content 設(shè)為 YES
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoadsForMedia</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
通過以上配置,即可實(shí)現(xiàn) https 請(qǐng)求本地資源
<script type="text/javascript" src="https://localhost:60000/hi.js"></script>
- (void)loadRemoteRequest {
if (_wkWebView) {
[_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://smallfan.net/demo.html"]]];
}
}
- (void)loadLocalRequest {
if (_wkWebView) {
[_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://localhost:%ld/index.html", [[LocalWebServerManager sharedInstance] port] ] ]]];
}
}
小結(jié)
實(shí)際上這種方式實(shí)現(xiàn) WKWebView 離線加載,屬于奇技淫巧。因?yàn)?Apple 封閉的生態(tài),很多時(shí)候想優(yōu)化一些既有的東西舉步維艱,只能不斷探索。
從這個(gè)角度來看,還是 Python 好玩點(diǎn),23333 ...
關(guān)于 local web server 中有些問題,筆者并未來得及作更深入研究,以下列舉一些可能性問題,歡迎大家一起探討:
- 資源訪問權(quán)限安全問題
- APP前后臺(tái)切換時(shí),服務(wù)重啟性能耗時(shí)問題
- 服務(wù)運(yùn)行時(shí),電量及CPU占有率問題
- 多線程及磁盤IO問題
最后,丟個(gè)Demo出來,Biu...
Demo地址:LocalWebServer
歡迎關(guān)注我的簡(jiǎn)書,我是程序猿小風(fēng)扇,請(qǐng)多多指教
Github:Smallfan