之前寫過一篇補丁更新的文章,那套設計把狀態機做得比較完整。這次做一個精簡的最小化實現,方便直接集成到項目裡。為了讓邏輯通用,這裡剝離掉對 AFNetworking 和 ReactiveCocoa 的依賴,全部改用系統 API。
先交代動機。這大概會成為我博客裡一個固定的系列框架——不然過一陣子自己回頭看,也只是一堆乾巴巴的代碼,看不出當初為什麼這麼設計。
這次要主動「從簡」,原因有三:
所以這篇文章的意義,其實在於把已有的熱更新代碼做減法——越簡單越好維護。
下面一步步實現。
封裝一個方法,用 block 把結果拋出去:
- (void)fetchPatchInfo:(NSString *)urlStr
completionHandler:(void (^)(NSDictionary *patchInfo, NSError *error))completionHandler {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSDictionary *patchInfo = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
completionHandler(patchInfo, error);
}];
[dataTask resume];
}
基於 block,調用側就非常乾淨:
[self fetchPatchInfo:@"https://raw.githubusercontent.com/ios122/ios_assets_hot_update/master/res/patch_04.json"
completionHandler:^(NSDictionary *patchInfo, NSError *error) {
if (!error) {
NSLog(@"patchInfo:%@", patchInfo);
} else {
NSLog(@"fetchPatchInfo error: %@", error);
}
}];
核心是下載完成後計算文件 md5,剩下的就是字符串比較。使用前要引入系統庫:
#include <CommonCrypto/CommonDigest.h>
/**
* 獲取文件的 md5 值
*/
- (NSString *)mcMd5HashOfPath:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path isDirectory:nil]) { return @""; }
NSData *data = [NSData dataWithContentsOfFile:path];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5(data.bytes, (CC_LONG)data.length, digest);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
直接複用 NSUserDefaults 就好,不必為此引入數據庫:
NSString *sourcePatchKey = @"SOURCE_PATCH"; [[NSUserDefaults standardUserDefaults] setObject:patchInfo forKey:sourcePatchKey]; patchInfo = [[NSUserDefaults standardUserDefaults] objectForKey:sourcePatchKey]; NSLog(@"patchInfo:%@", patchInfo);
規則很簡單:補丁 md5 為 e963ed645c50a004697530fa596f180b,就解壓到 Library/Caches/patch/e963ed645c50a004697530fa596f180b。
- (NSString *)cachePathFor:(NSString *)patchMd5 {
NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
return [[[libraryPaths objectAtIndex:0] stringByAppendingFormat:@"/Caches/patch"]
stringByAppendingPathComponent:patchMd5];
}
使用起來就是下載完成後拼接路徑:
NSString *urlStr = [patchInfo objectForKey:@"url"];
[weak_self downloadFileFrom:urlStr completionHandler:^(NSURL *location, NSError *error) {
if (error) {
NSLog(@"download file url:%@ error: %@", urlStr, error);
return;
}
NSString *cachePath = [weak_self cachePathFor:[patchInfo objectForKey:@"md5"]];
NSLog(@"location:%@ cachePath:%@", location, cachePath);
}];
解壓推薦用 SSZipArchive,一行代碼:
[SSZipArchive unzipFileAtPath:location.path
toDestination:patchCachePath
overwrite:YES
password:nil
error:&error];
如果機器上還沒裝 CocoaPods,可以用 Homebrew 安裝:
brew install CocoaPods
建議放在「下載並解壓成功之後」再更新,因為讀取圖片時也要依賴這份信息判斷該去哪個目錄找。至於刪除某個補丁,按目前設計有一個偷懶做法:在服務器上放一個空的資源包,讓 md5 變掉即可。
NSString *sourcePatchKey = @"SOURCE_PATCH"; [[NSUserDefaults standardUserDefaults] setObject:patchInfo forKey:sourcePatchKey];
下載完成後通過 block 傳出臨時文件位置:
- (void)downloadFileFrom:(NSString *)urlStr
completionHandler:(void (^)(NSURL *location, NSError *error))completionHandler {
NSURL *url = [NSURL URLWithString:urlStr];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url
completionHandler:^(NSURL *location,
NSURLResponse *response,
NSError *error) {
completionHandler(location, error);
}];
[task resume];
}
其實不必用 fileExistsAtPath:,直接調 pathForResource:ofType: 就夠了——找不到時它返回 nil,判斷返回值即可:
NSString *imgPath = [mainBundle pathForResource:imgName ofType:@"png"];
最終形態是一個 UIImage 的分類,對外只暴露兩個方法:一個智能讀圖,一個觸發補丁更新。
#import <UIKit/UIKit.h> @interface UIImage (imageNamed_bundle_) // 智能加載圖片:優先緩存目錄,其次 ipa 包 + (UIImage *)yf_imageNamed:(NSString *)imgName; // 從指定接口檢查並更新補丁 + (void)yf_updatePatchFrom:(NSString *)pathInfoUrlStr; @end
在 App 啟動時調用一次檢查:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *patchUrlStr = @"https://raw.githubusercontent.com/ios122/ios_assets_hot_update/master/res/patch_04.json";
[UIImage yf_updatePatchFrom:patchUrlStr];
return YES;
}
內部實現:
#import "UIImage+imageNamed_bundle_.h"
#import <SSZipArchive/SSZipArchive.h>
@implementation UIImage (imageNamed_bundle_)
+ (NSString *)yf_sourcePatchKey {
return @"SOURCE_PATCH";
}
#pragma mark - 更新補丁
+ (void)yf_updatePatchFrom:(NSString *)pathInfoUrlStr {
[self yf_fetchPatchInfo:pathInfoUrlStr completionHandler:^(NSDictionary *patchInfo, NSError *error) {
if (error) {
NSLog(@"fetchPatchInfo error: %@", error);
return;
}
NSString *urlStr = [patchInfo objectForKey:@"url"];
NSString *md5 = [patchInfo objectForKey:@"md5"];
NSString *oriMd5 = [[[NSUserDefaults standardUserDefaults] objectForKey:[self yf_sourcePatchKey]]
objectForKey:@"md5"];
// md5 相同,無需更新
if ([oriMd5 isEqualToString:md5]) { return; }
[self yf_downloadFileFrom:urlStr completionHandler:^(NSURL *location, NSError *error) {
if (error) {
NSLog(@"download file url:%@ error: %@", urlStr, error);
return;
}
NSString *patchCachePath = [self yf_cachePathFor:md5];
[SSZipArchive unzipFileAtPath:location.path
toDestination:patchCachePath
overwrite:YES
password:nil
error:&error];
if (error) {
NSLog(@"unzip error, urlStr:%@ error:%@", urlStr, error);
return;
}
// 解壓成功後才更新緩存信息
[[NSUserDefaults standardUserDefaults] setObject:patchInfo forKey:[self yf_sourcePatchKey]];
}];
}];
}
#pragma mark - 讀取圖片
+ (NSString *)yf_relativeCachePathFor:(NSString *)md5 {
return [@"patch" stringByAppendingPathComponent:md5];
}
+ (UIImage *)yf_imageNamed:(NSString *)imgName {
NSString *md5 = [[[NSUserDefaults standardUserDefaults] objectForKey:[self yf_sourcePatchKey]]
objectForKey:@"md5"];
NSString *relativeCachePath = md5 ? [self yf_relativeCachePathFor:md5] : nil;
return [self yf_imageNamed:imgName bundle:@"main" cacheDir:relativeCachePath];
}
+ (UIImage *)yf_imageNamed:(NSString *)imgName
bundle:(NSString *)bundleName
cacheDir:(NSString *)cacheDir {
NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
bundleName = [NSString stringWithFormat:@"%@.bundle", bundleName];
NSString *ipaBundleDir = [NSBundle mainBundle].resourcePath;
NSString *cacheBundleDir = ipaBundleDir;
if (cacheDir) {
cacheBundleDir = [[[libraryPaths objectAtIndex:0] stringByAppendingFormat:@"/Caches"]
stringByAppendingPathComponent:cacheDir];
}
imgName = [NSString stringWithFormat:@"%@@3x", imgName];
// 先找緩存目錄
NSString *bundlePath = [cacheBundleDir stringByAppendingPathComponent:bundleName];
NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
NSString *imgPath = [bundle pathForResource:imgName ofType:@"png"];
// 緩存裡沒有,回落到 ipa 包
if (!imgPath && ![ipaBundleDir isEqualToString:cacheBundleDir]) {
bundlePath = [ipaBundleDir stringByAppendingPathComponent:bundleName];
bundle = [NSBundle bundleWithPath:bundlePath];
imgPath = [bundle pathForResource:imgName ofType:@"png"];
}
static NSString *model;
if (!model) { model = [[UIDevice currentDevice] model]; }
if ([model isEqualToString:@"iPad"]) {
NSData *imageData = [NSData dataWithContentsOfFile:imgPath];
return [UIImage imageWithData:imageData scale:2.0];
}
return [UIImage imageWithContentsOfFile:imgPath];
}
#pragma mark - 網絡
+ (void)yf_fetchPatchInfo:(NSString *)urlStr
completionHandler:(void (^)(NSDictionary *patchInfo, NSError *error))completionHandler {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:urlStr];
NSURLSessionDataTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSDictionary *patchInfo = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
completionHandler(patchInfo, error);
}];
[task resume];
}
+ (void)yf_downloadFileFrom:(NSString *)urlStr
completionHandler:(void (^)(NSURL *location, NSError *error))completionHandler {
NSURL *url = [NSURL URLWithString:urlStr];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url
completionHandler:^(NSURL *location,
NSURLResponse *response,
NSError *error) {
completionHandler(location, error);
}];
[task resume];
}
+ (NSString *)yf_cachePathFor:(NSString *)patchMd5 {
NSArray *libraryPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
return [[[libraryPaths objectAtIndex:0] stringByAppendingFormat:@"/Caches"]
stringByAppendingPathComponent:[self yf_relativeCachePathFor:patchMd5]];
}
@end
這樣一來,業務代碼裡加載圖片變得非常清爽:
UIImage *image = [UIImage yf_imageNamed:@"sub/sample"]; self.sampleImageView.image = image;
如果熱更新生效,運行後看到的應該是一個錘子圖片。
我覺得這篇文章最大的特點,是完整記錄了一次「優化並簡化問題」的過程。示例代碼前後有些地方不太統一,是因為我並不是先有完整方案再動手寫博客,而是借寫博客來梳理思路、簡化邏輯。這樣一來,寫博客就不只是一次耗時的知識分享,而成了一件幫自己思考的工具。