iOS备忘录ios basicReact Native

IOS 热修复JSPatch

2016-03-15  本文已影响2644人  倚楼听风雨wing

1.为什么要引入JSPatch

相信对于维护已经发版了的IOS的朋友都有遇到过程序已经上架了,可是现在突然发现有一个十分紧急的问题需要修复。及时我们可以走苹果的加急通道,但这并不意味着我们可以不走苹果的审核,整个流程下来也得两三天。可是如果我们的项目引入了JSPatch我们就可以避免这样的问题发生,动态的修复APP的bug。

2.浅谈JSPatch实现原理

首先需要普及的是:OC是一门动态运行的语言,所有的类的创建和方法的调用都是通过Object-C Runtime在运行时进行的。JSPathc就是抓住OC的这一特点,以IOS内置的JavaScriptCore.framework作为JS引擎,从JS传递要调用的函数名和类名到OC,再使用NSInvocation动态调用对应的方法。例:

    Class class = NSClassFromString(@"UIViewController");
    id controller = [class new];
    SEL selector = NSSelectorFromString(@"viewDidLoad");
    [controller performSelector:selector];

如果想要深入了解其原理,可以查看作者的原文章
地址:http://www.csdn.net/article/2015-10-29/2826084

3.简单搭建JSPath项目

JSPatch下载地址:https://github.com/wangyansnow/JSPatch
只需要把JSPatch这个文件夹拖入到项目中,然后把github中下载项目的demo.js文件拖入到项目中。然后在APPDelegate编写如下代码:

#import "AppDelegate.h"
#import "JPEngine.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [JPEngine startEngine];
    
    NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"demo.js" ofType:nil];
    [JPEngine evaluateScriptWithPath:jsPath];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    ViewController *rootViewController = [[ViewController alloc] init];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    self.window.rootViewController = navigationController;
    [self.window makeKeyAndVisible];
    
    return YES;
}

@end

再在ViewController.m中编写如下代码:


- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 50)];
    [btn setTitle:@"Push JPTableViewController" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(handleBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:btn];
}

- (void)handleBtn:(UIButton *)btn {
    
}

最后在吧demo.js里面的JPViewController修改为ViewController

Paste_Image.png

4.最后介绍一个OC代码转js的网址

只需要在其中输入OC代码然后店家Covert即可转换为对应的js代码。【复杂OC代码还是需要自己写对应的js】
网址:http://bang590.github.io/JSPatchConvertor/

上一篇 下一篇

猜你喜欢

热点阅读