单军华
2018-07-11 7b02207537d35bfa1714bf8beafc921f717d100a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
//  PPNetworkCache.m
//  PPNetworkHelper
//
//  Created by AndyPang on 16/8/12.
//  Copyright © 2016年 AndyPang. All rights reserved.
//
 
#import "PPNetworkCache.h"
#import "YYCache.h"
 
static NSString *const kPPNetworkResponseCache = @"kPPNetworkResponseCache";
 
@implementation PPNetworkCache
static YYCache *_dataCache;
 
+ (void)initialize {
    _dataCache = [YYCache cacheWithName:kPPNetworkResponseCache];
}
 
+ (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    //异步缓存,不会阻塞主线程
    [_dataCache setObject:httpData forKey:cacheKey withBlock:nil];
}
 
+ (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    return [_dataCache objectForKey:cacheKey];
}
 
+ (NSInteger)getAllHttpCacheSize {
    return [_dataCache.diskCache totalCost];
}
 
+ (void)removeAllHttpCache {
    [_dataCache.diskCache removeAllObjects];
}
 
+ (NSString *)cacheKeyWithURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    if(!parameters || parameters.count == 0){return URL;};
    // 将参数字典转换成字符串
    NSData *stringData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];    
    return [NSString stringWithFormat:@"%@%@",URL,paraString];
}
 
 
@end