@@ -65,8 +65,34 @@ - (void)parseWithURLRequest:(NSURLRequest *)URLRequest completionBlock:(void (^)
6565 }];
6666 return ;
6767 }
68+ NSString *cacheKey = [self cacheKey: URLRequest.URL ];
69+ if ([[NSFileManager defaultManager ] fileExistsAtPath: [self cachePath: cacheKey]]) {
70+ NSString *cachePath = [self cachePath: cacheKey];
71+ [parseQueue addOperationWithBlock: ^{
72+ NSData *data = [NSData dataWithContentsOfFile: cachePath];
73+ [self parseWithData: data cacheKey: cacheKey completionBlock: ^(SVGAVideoEntity * _Nonnull videoItem) {
74+ if (completionBlock) {
75+ [[NSOperationQueue mainQueue ] addOperationWithBlock: ^{
76+ completionBlock (videoItem);
77+ }];
78+ }
79+ } failureBlock: ^(NSError * _Nonnull error) {
80+ [self clearCache: cacheKey];
81+ if (failureBlock) {
82+ [[NSOperationQueue mainQueue ] addOperationWithBlock: ^{
83+ failureBlock (error);
84+ }];
85+ }
86+ }];
87+ }];
88+ return ;
89+ }
6890 [[[NSURLSession sharedSession ] dataTaskWithRequest: URLRequest completionHandler: ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
6991 if (error == nil && data != nil ) {
92+ // save to file
93+ NSString *path = [self cachePath: [self cacheKey: URLRequest.URL ]];
94+ BOOL result = [data writeToFile: path atomically: true ];
95+ // NSLog(@"Save to cache result: %@", @(result));
7096 [self parseWithData: data cacheKey: [self cacheKey: URLRequest.URL ] completionBlock: ^(SVGAVideoEntity * _Nonnull videoItem) {
7197 if (completionBlock) {
7298 [[NSOperationQueue mainQueue ] addOperationWithBlock: ^{
@@ -360,6 +386,11 @@ - (nullable NSString *)cacheDirectory:(NSString *)cacheKey {
360386 return [cacheDir stringByAppendingFormat: @" /%@ " , cacheKey];
361387}
362388
389+ - (nullable NSString *)cachePath : (NSString *)cacheKey {
390+ NSString *cacheDir = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES ) firstObject ];
391+ return [cacheDir stringByAppendingFormat: @" /%@ .svga" , cacheKey];
392+ }
393+
363394- (NSString *)MD5String : (NSString *)str {
364395 const char *cstr = [str UTF8String ];
365396 unsigned char result[16 ];
0 commit comments