iOS热更新,基于JSPatch进行的封装ZXJSPatcheHelper

JSPatch

  • JSPatch的Github主页:https://github.com/bang590/JSPatch
  • JSPatch的转换工具:https://github.com/bang590/JSPatchConvertor
  • JSPatch官网:http://www.jspatch.com/

关于JSPatch的一些思考

JSPatch的原理就不在写了(不想互相copy...),网上文章太多,建议各位可以有选择性的阅读,其实最好的学习JSPatch就是我上面提供的三个链接,专业、实时、官方可信赖。

在使用的时候需要考虑的5个问题:
  • 云端存储策略
  • 版本控制(多版本并存)
  • 覆盖范围
  • 本地缓存策略
  • 本地加载方式

ZXJSPatchHelper说明

从没想过写这个玩意,感觉(JSPatch官方已经做得很完整,很专业,很商业化了)纯粹想不明白JSPatch为什么要进行象征性的收费,因为JSPatch源码是基于MIT(建议百度下),而以上业务的设计并没有开源出来,所以就自己写了一个小工具。ZXJSPatchHelper目前只针对第5个问题进行了处理(上午过来上班才开始写的...后续会更新),前3个问题需要服务端进行配合,稍后写一个PHP版本的demo。

如何使用ZXJSPatchHelper

  1. pod 'JSPatch'
    pod 'AFDownloadRequestOperation'
  2. AppDelegate.m导入 #import"ZXJSPatchHelper.h"
  3. didFinishLaunchingWithOptions中添加开始使用:
[[ZXJSPatchHelper shareZXJSPatchHelper] startJSPatch:@"demo" withLoadType:JPLoadScriptTypeJSFile];

源码

.h

//
//  ZXJSPatchHelper.h
//  ZXAutoLayout
//
//  Created by Hawk on 5/12/16.
//  Copyright © 2016 鹰. All rights reserved.
//

#import 

/**
 *  Four loaded ways, according to the source of distinction js
 */
typedef NS_ENUM(NSInteger, JPLoadScriptType){
    /**
     *  JS Source string
     */
    JPLoadScriptTypeNSString = 0,
    /**
     *  a url can request
     */
    JPLoadScriptTypeNSURL,
    /**
     *  project sources
     */
    JPLoadScriptTypeSourceJS,
    /**
     *  App Document 
     */
    JPLoadScriptTypeJSFile,
};

@interface ZXJSPatchHelper : NSObject

+ (instancetype)shareZXJSPatchHelper;

#pragma mark - API

- (void)startJSPatch:(NSString *)script withLoadType:(JPLoadScriptType)loadType;

@end

.m

//
//  ZXJSPatchHelper.m
//  ZXAutoLayout
//
//  Created by Hawk on 5/12/16.
//  Copyright © 2016 鹰. All rights reserved.
//

#import "ZXJSPatchHelper.h"
#import "JPEngine.h"
#import "AFDownloadRequestOperation.h"

const NSString * kJSHost = @"http://weixin.qiuyouzone.com/WXGZPT/ios_js/mq.js";

@implementation ZXJSPatchHelper

+ (instancetype)shareZXJSPatchHelper{
    
    static ZXJSPatchHelper * shareInstance = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        shareInstance = [[self alloc] init];
    });
    return shareInstance;
}

#pragma mark - API

- (void)startJSPatch:(NSString *)script withLoadType:(JPLoadScriptType)loadType {
    
    NSCAssert(script, @"script must not be nil !");
    
    switch (loadType) {
            
        case JPLoadScriptTypeNSString:
            [self loadNSStringJS:script];
            break;
        case JPLoadScriptTypeNSURL:
            [self loadNSURLJS:script];
            break;
        case JPLoadScriptTypeSourceJS:
            [self loadSourceJS:script];
            break;
        case JPLoadScriptTypeJSFile:
            [self asyncFetchJSSourceFile:script];
            break;
            
        default:
            break;
    }
}

- (void)asyncFetchJSSourceFile:(NSString *)script {
    
    NSString *filePath = [[self docuemntPath] stringByAppendingString:[NSString stringWithFormat:@"/%@.js",script]];
    
//    // clean local js file whenever request new js source from server
//    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
//        
//        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
//    }
    
    NSLog(@"filePatch = %@",filePath);
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://weixin.qiuyouzone.com/WXGZPT/ios_js/mq.js"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:3600];
    
    AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:filePath shouldResume:YES];
    
    __weak typeof (self) weakSelf = self;
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *  operation, id responseObject) {
        
        [weakSelf loadFileJS:script];
        
    } failure:^(AFHTTPRequestOperation *  operation, NSError *  error) {
        
        
    }];
    
    operation.shouldOverwrite = YES;
    
    [operation start];
    
    
}

#pragma mark - private

- (void)loadNSStringJS:(NSString *)script {
    
    [JPEngine startEngine];
    [JPEngine evaluateScript:script];
    
}

- (void)loadNSURLJS:(NSString *)script {
    
    [JPEngine startEngine];
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:script]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *script = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [JPEngine evaluateScript:script];
    }];
    
}

- (void)loadSourceJS:(NSString *)script {
    
    [JPEngine startEngine];
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:script ofType:@"js"];
    NSString *src = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
    [JPEngine evaluateScript:src];
    
}

- (void)loadFileJS:(NSString *)script {
    
    [JPEngine startEngine];
    NSString *sourcePath = [[self docuemntPath] stringByAppendingString:[NSString stringWithFormat:@"/%@.js",script]];
    NSString *src = [NSString stringWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
    [JPEngine evaluateScript:src];
    
}

#pragma mark - mothods

- (NSString *)docuemntPath
{
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *ourDocuemntPath = [documentPaths objectAtIndex:0];
    return ourDocuemntPath;
}

@end

你可能感兴趣的:(iOS热更新,基于JSPatch进行的封装ZXJSPatcheHelper)