IOS产品开发中经常会遇到这种状况,线上发现一个严重bug,多是一个crash,多是一个功能没法使用,这时能作的只是赶忙修复Bug而后提交等待漫长的审核,即便申请加急也不会快到那里去,即便审核完了以后,还要盼望着用户快点升级,用户不升级仍是在存在一样的漏洞,这样的状况让开发者付出了很大的成本才能完成Bug的修复。javascript
JSPath就是为了解决这样的问题而出现的,只须要在项目中引入极小的JSPatch引擎,就能够还用JavaScript语言调用Objective-C的原生API,动态更新APP,修复BUG。java
JSPaht自己是开源项目,项目地址:http://jspatch.com/,github地址: https://github.com/bang590/JSPatch
在他的官网上面给出了一个例子:ios
1 @implementation JPTableViewController 2 ... 3 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 4 { 5 NSString *content = self.dataSource[[indexPath row]]; //可能会超出数组范围致使crash 6 JPViewController *ctrl = [[JPViewController alloc] initWithContent:content]; 7 [self.navigationController pushViewController:ctrl]; 8 } 9 ... 10 @end
能够经过下发下面的JavaScript代码修复这个bug:git
1 //JS 2 defineClass("JPTableViewController", { 3 //instance method definitions 4 tableView_didSelectRowAtIndexPath: function(tableView, indexPath) { 5 var row = indexPath.row() 6 if (self.dataSource().length > row) { //加上判断越界的逻辑 7 var content = self.dataArr()[row]; 8 var ctrl = JPViewController.alloc().initWithContent(content); 9 self.navigationController().pushViewController(ctrl); 10 } 11 } 12 }, {})
JSPtch须要一个后台服务用来下发和管理脚本,并须要处理传输安全等。github
注册获取AppKey
在平台上面注册一个帐户,新建一个App能够拿到对应的AppKey。数组
导入SDK到项目中
SDK地址:http://jspatch.com/Index/sdk
当前下载下来的SDK版本名称是:JSPatch 2.framework
,须要去掉中间的空格,否则导入项目的时候会报错。
导入项目的时候要选择Copy items if needed
。
还须要添加对于的依赖框架JavaScriptCore.framework
和libz.tbd
.安全
添加JSPatch代码
在AppDelegate.m中添加代码:服务器
1 #import "AppDelegate.h" 2 #import <JSPatch/JSPatch.h> 3 4 @implementation AppDelegate 5 6 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 7 [JSPatch startWithAppKey:@"f78378d77e5783e8"]; 8 [JSPatch sync]; 9 return YES; 10 } 11 @end
在平台中上传js修复文件
为了简单咱们只上传一个简单的UIAlertView
,弹出一个提示框:app
1 ar alertView = require('UIAlertView').alloc().init(); 2 alertView.setTitle('Alert'); 3 alertView.setMessage('AlertView from js'); 4 alertView.addButtonWithTitle('OK'); 5 alertView.show();
用JavaScript实例化了UIAlertView,文件名须要命名为main.js
。框架
从服务器下发到客户端
把main.js
上传到服务器上,下发到版本为1.0的客户端上面。
在请求服务加载脚本的时候出现了一个错误:The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.
这个错误出现的缘由是ios9引入了新特性App Transport Security(ATS)
,简单来讲就是APP内部的请求必须使用HTTPS协议。
很明显这里的url并无使用https,咱们能够经过设置先规避掉这个问题:
1.在info.plist中添加NSAppTransportSecurity类型为Dictionary. 2.在NSAppTransportSecurity中添加NSAllowsArbitraryLoads类型为Boolean,值为YES
运行效果: