基于 LocalWebServer 实现 WKWebView 离线资源加载

本文系Smallfan(程序猿小风扇)原创内容,转载请在文章开头显眼处注明作者和出处。

背景

笔者在《WKWebView》一文中提到过,WKWebView 在独立于 app 进程之外的进程中执行网络请求,请求数据不经过主进程,因此,在 WKWebView 上直接使用 NSURLProtocol 无法拦截请求。所以如果需要使用到拦截请求,有种可行地方案是使用苹果开源的 Webkit2 源码暴露的私有API(详见原文第3小节:NSURLProtocol问题)。
但使用私有API,必然带来以下几个问题:

  • 审核风险
  • 拦截http/https时,post请求body丢失
  • 如使用ajax hook方式,可能存在 post header字符长度限制Put类型请求异常

由此看来,在 iOS11 WKURLSchemeHandler [探究] 到来之前,私有API并不那么完美。
所幸通过寻找发现,iOS系统上具备搭建服务器能力,理论上对实现 WKWebView 离线资源加载 存在可能性。

分析

基于iOS的local web server,目前大致有以下几种较为完善的框架:

  • CocoaHttpServer (支持iOS、macOS及多种网络场景)
  • GCDWebServer (基于iOS,不支持 https 及 webSocket)
  • Telegraph (Swift实现,功能较上面两类更完善)

因为目前大部分APP已经支持ATS,且国内大部分项目代码仍采用OC实现,故本文将以 CocoaHttpSever 为基础进行实验。
Telegraph 是为补充 CocoaHttpSever 及 GCDWebServer 不足而诞生,对于纯Swift项目,推荐使用 Telegraph

初出茅驴

在 project工程文件 中引入 CocoaHttpServer 之后,

  1. 首先实现一个服务管理。
#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(@"启动失败");
        }
    }
    
}

- (void)stop {
    if (_httpServer && [_httpServer isRunning]) {
        [_httpServer stop];
    }
}

@end
  1. 然后选择其启动时机,一般选择在 AppDelegate 中或 WKWebView 请求之前。
- (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];
}
  1. 在 project工程 中引入相对资源目录(蓝色文件夹),在该目录中实现一个 index.htmlhi.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>恭喜你 服务器运行成功!</h1>
        <h5><br>点击下面按钮试一下</h5>
        <input type='button' value='调用本地js资源中的方法' onclick='invokeAlert()'/>
    </center>
</body>
</html>
function invokeAlert() {
    alert('Perfect!')
}
  1. 通过WKWebView访问 http://localhost:60000/index.html 即可。

通过以上4步,即可开启iOS本地http服务,通过WKWebView访问本地的html资源。

不过本文目的是 “基于LocalWebServer实现WKWebView离线资源加载”,所谓离线资源加载,指的是:页面资源在远端服务器,而页面中的部分资源在iOS本地沙盒中。
放在上面的例子上,也就是 index.html 应该在远程的 nginx 或 apache 等服务上运行,而 hi.js 应该存放在APP的资源目录之中。

此举是否可行呢?我们试试看。
index.html 改名为 demo.html 配置在 http://smallfan.net 中,直接进行访问

- (void)loadRemoteRequest {
    if (_wkWebView) {
        [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://smallfan.net/demo.html"]]];
    }
}

实验结果:可行。
也就是说,通过以下该方式实现:HTML页面内资源允许请求本地服务器

<script type="text/javascript" src="http://localhost:60000/hi.js"></script>

支持https

正如前面所提:支持ATS已经成为一个正确而有效的选择。

SafariApple WebKit 中:在https页面内,不允许http请求存在,否则一概会被block。

因此如果已经支持了https,那么页面中的 http://localhost:60000/hi.js 也必须 支持https才行。问题是,页面https我们可以采用CA颁发的合法证书进行双向或单向认证,而localhost并不是一个合法的host,也就是说我们需要为它实现一个自签名证书。

1. 实现local server自签名证书

因为iOS开发使用MacOS,以下行为默认系统已经安装OpenSSL。

首先到 OpenSSL官网 下载最新版本,解压后在app目录中找到CA.sh,拷贝到根目录,然后运行

% sh ~/CA.sh -newca

运行完后会生成一个demoCA的目录,里面存放了CA的证书和私钥,同时记住自己设置的授权密码。
创建一个目录

% mkdir server

然后创建一个私钥

% openssl genrsa -out server/server-key.pem 2048

创建证书请求

% openssl req -new -out server/server-req.csr -key server/server-key.pem

此时终端会要求你填写地区、姓名等信息,Common Name 这一项必须填 localhost 或者 127.0.0.1 ,如果填写127.0.0.1,那么页面中请求只能使用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

将证书导出成浏览器支持的.p12格式,记得导出密码(本文为: b123456)

% openssl pkcs12 -export -clcerts -in server/server-cert.pem -inkey server/server-key.pem -out server/server.p12

自此,自签名证书生成完成。

2. 配置自签名证书

将p12文件导入 project工程 中的资源目录中,
同时新建一个 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文件导出密码
    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.mstartConnection 方法中

[settings setObject:(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(NSString *)kCFStreamSSLLevel];

替换为

[settings setObject:@"2" forKey:GCDAsyncSocketSSLProtocolVersionMin];
[settings setObject:@"2" forKey:GCDAsyncSocketSSLProtocolVersionMax];

同时在启动 HTTPServer(调用 startServer )之前,使用 setConnectionClass 方法将 HTTPConnecdtion 替换为 MyHTTPConnection

[_httpServer setConnectionClass:[MyHTTPConnection class]];

自此,https服务配置完成。

3. WKWebView证书配置

对于自签名证书,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设置

Info.plist 中,找到 App Transport Security Settings 项,在其中增加一项 Allow Arbitrary Loads in Web Content 设为 YES

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoadsForMedia</key>
        <true/>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
        <key>NSAllowsArbitraryLoads</key>
        <false/>
    </dict>

通过以上配置,即可实现 https 请求本地资源

<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] ] ]]];
    }
}

小结

实际上这种方式实现 WKWebView 离线加载,属于奇技淫巧。因为 Apple 封闭的生态,很多时候想优化一些既有的东西举步维艰,只能不断探索。
从这个角度来看,还是 Python 好玩点,23333 ...

关于 local web server 中有些问题,笔者并未来得及作更深入研究,以下列举一些可能性问题,欢迎大家一起探讨:

  • 资源访问权限安全问题
  • APP前后台切换时,服务重启性能耗时问题
  • 服务运行时,电量及CPU占有率问题
  • 多线程及磁盘IO问题

最后,丢个Demo出来,Biu...
Demo地址:LocalWebServer

欢迎关注我的简书,我是程序猿小风扇,请多多指教
Github:Smallfan

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,596评论 4 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • 等雨停,等风来, 等傍晚的烟霞离开。 车来人往,卷走多少离殇。 等不来的人,不放还能怎样? 不如就这样忘。 等夜深...
    已不用了啊阅读 148评论 0 0
  • 你心底最踏实的温暖与根基起源于哪里呢?一个村落、一个人、一件事、或眼前的一片美景,那一刻你是一块糖,你是氧气 ,是...
    希欣阅读 210评论 2 3
  • 第一、关于df和du 1、df : 查看磁盘的容量 1)rootfs : 系统启动时内核载入内存之后,在挂载真正...
    bewhyy阅读 839评论 0 0