腾讯开源的 Hybrid 框架 VasSonic 这两天被推出来了,今天知乎上也是热评如潮。上面详细的说明了 VasSonic 的发展史。
更多精彩内容请看 web 前端中文站
http://www.lisa33xiaoq.net 可按 Ctrl + D 进行收藏
从目前来看,以后微信的小程序打开速度将更快了。下面说说 VasSonic 的主要原理。
VasSonic 的主要原理
VasSonic 在内容请求方面用了三招:
- 动态缓存
- 增量更新
- 并行加载
通过对 HTML 内容添加注释来定义了一个自定义的格式,对 HTML 文档进行分块。
- 动态缓存:指在页面范围内,对分块后的同容进行更细化(全局、局部)的缓存。
- 增量更新:有缓存的情况下,只对分块后的局部内容进行增量更新。
- 并行加载:VasSonic 使用终端应用层原生传输通道取代系统浏览器内核自身资源传输通道来请求页面主资源。就是通过 VasSonic 在WebView 初始化过程中时,同步并行从服务器加载页面,而不是 webview 初始化后再去请求。
下面回到今天的主题。iOS 对接 Hybrid 框架 VasSonic 教程。
iOS 使用
步骤 1:导入并声明
构建声波框架 将 Sonic.framework 添加到主项目中的依赖项。然后@import Sonic 注册 SonicURLProtocol:
[NSURLProtocol registerClass:[SonicURLProtocol class]]; @interface SonicWebViewController : UIViewController<SonicSessionDelegate,UIWebViewDelegate>
步骤 2:实施 SonicSessionDelegate
#pragma mark - Sonic Session Delegate /* * 调用回来时,声波会发送请求。 */ - (void)sessionWillRequest:(SonicSession *)session { //This callback can be used to set some information, such as cookie and UA. } /* *当 Sonic 要求 WebView 重新加载时回调,例如模板更改或发生错误。 */ - (void)session:(SonicSession *)session requireWebViewReload:(NSURLRequest *)request { [self.webView loadRequest:request]; }
步骤 3:在 WebView ViewController 中使用 Sonic
- (instancetype)initWithUrl:(NSString *)aUrl { if (self = [super init]) { self.url = aUrl; //用 URL 创建一个声音会话。 [[SonicClient sharedClient] createSessionWithUrl:self.url withWebDelegate:self]; } return self; } /* * 在 WebView 初始化后立即发送 Sonic 属性的请求。 */ - (void)loadView { [super loadView]; self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds]; self.webView.delegate = self; self.view = self.webView; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]]; /* * 如果 SonicSession 不为空,Sonic 使用自定义 SonicWebRequest 而不是原始网络请求。 */ if ([[SonicClient sharedClient] sessionWithWebDelegate:self]) { [self.webView loadRequest:sonicWebRequest(request)]; }else{ [self.webView loadRequest:request]; } }
步骤 4:通过 JavaScript 回调与网站交互。
- (void)getDiffData:(NSDictionary *)option withCallBack:(JSValue *)jscallback { /* * ViewController 发送 Sonic 请求并通过回调返回结果。 */ [[SonicClient sharedClient] sonicUpdateDiffDataByWebDelegate:self.owner completion:^(NSDictionary *result) { /* * 返回结果。 */ NSData *json = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonStr = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding]; JSValue *callback = self.owner.jscontext.globalObject; [callback invokeMethod:@"getDiffDataCallback" withArguments:@[jsonStr]]; }]; }
<p> 步骤 5:删除声音会话。 </p> <pre class="brush:plain;"> – (void)dealloc { [[SonicClient sharedClient ] removeSessionWithWebDelegate:self ]; }
OK,经过上面 5 个步骤,一个完整的 IOS 实例就完成了。赶紧试试吧。
【注:本文源自网络文章资源,由站长整理发布】