您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

實現 iOS 圖片等資源文件的熱更新(四):一個最小化的補丁更新邏輯

編輯:iOS 開發綜合

簡介

之前寫過一篇補丁更新的文章,那套設計把狀態機做得比較完整。這次做一個精簡的最小化實現,方便直接集成到項目裡。為了讓邏輯通用,這裡剝離掉對 AFNetworking 和 ReactiveCocoa 的依賴,全部改用系統 API。

為什麼要再寫一遍

先交代動機。這大概會成為我博客裡一個固定的系列框架——不然過一陣子自己回頭看,也只是一堆乾巴巴的代碼,看不出當初為什麼這麼設計。

這次要主動「從簡」,原因有三:

  1. 補丁更新的狀態確實可以設計得很複雜,但對我們的 App 來說沒那個必要。
  2. 我想演示一個邏輯相對完整的方案,又不想花太多時間去搭建演示場景。
  3. 簡化後的方案雖然樸素,但目前對項目來說夠用了。

所以這篇文章的意義,其實在於把已有的熱更新代碼做減法——越簡單越好維護。

基本思路

  1. App 啟動時請求一個服務器接口,拿到最新的圖片資源信息。
  2. 比對接口返回的 md5 字段與本地保存的 md5 是否一致,以此判斷有無更新。
  3. 若有更新,下載壓縮包並解壓到指定緩存目錄。緩存目錄以資源包的 md5 命名,避免不同版本互相污染。
  4. 讀取圖片時,優先從緩存目錄取;緩存裡沒有,再回落到 ipa 包內的資源。

下面一步步實現。

一、啟動時檢查更新

1.1 用原生網絡庫發請求

封裝一個方法,用 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);
    }
}];

1.2 校驗文件的 md5

核心是下載完成後計算文件 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;
}

1.3 本地緩存信息的存儲

直接複用 NSUserDefaults 就好,不必為此引入數據庫:

NSString *sourcePatchKey = @"SOURCE_PATCH";

[[NSUserDefaults standardUserDefaults] setObject:patchInfo forKey:sourcePatchKey];

patchInfo = [[NSUserDefaults standardUserDefaults] objectForKey:sourcePatchKey];
NSLog(@"patchInfo:%@", patchInfo);

二、補丁下載與解壓

2.1 按 md5 定位緩存目錄

規則很簡單:補丁 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);
}];

2.2 解壓到指定目錄

解壓推薦用 SSZipArchive,一行代碼:

[SSZipArchive unzipFileAtPath:location.path
                 toDestination:patchCachePath
                     overwrite:YES
                      password:nil
                         error:&error];

如果機器上還沒裝 CocoaPods,可以用 Homebrew 安裝:

brew install CocoaPods

2.3 什麼時候更新本地緩存信息

建議放在「下載並解壓成功之後」再更新,因為讀取圖片時也要依賴這份信息判斷該去哪個目錄找。至於刪除某個補丁,按目前設計有一個偷懶做法:在服務器上放一個空的資源包,讓 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];
}

四、判斷 bundle 中是否含有某文件

其實不必用 fileExistsAtPath:,直接調 pathForResource:ofType: 就夠了——找不到時它返回 nil,判斷返回值即可:

NSString *imgPath = [mainBundle pathForResource:imgName ofType:@"png"];

五、與原有 imageNamed: 邏輯合併

最終形態是一個 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;

如果熱更新生效,運行後看到的應該是一個錘子圖片。

後記

我覺得這篇文章最大的特點,是完整記錄了一次「優化並簡化問題」的過程。示例代碼前後有些地方不太統一,是因為我並不是先有完整方案再動手寫博客,而是借寫博客來梳理思路、簡化邏輯。這樣一來,寫博客就不只是一次耗時的知識分享,而成了一件幫自己思考的工具。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved