-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathETRequest.m
executable file
·378 lines (301 loc) · 11.1 KB
/
ETRequest.m
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//
// ETRequest.m
// 能量圈
//
// Created by vj on 2017/3/28.
// Copyright © 2017年 Weijie Zhu. All rights reserved.
//
#import "ETRequest.h"
#import "ETNetworkConfig.h"
#import "ETNetworkUtils.h"
NSString *const ETRequestCacheErrorDomain = @"com.moying.request.cache";
static dispatch_queue_t etrequest_cache_writing_queue(){
static dispatch_queue_t queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_queue_attr_t attr = DISPATCH_QUEUE_SERIAL;
if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0) {
attr = dispatch_queue_attr_make_with_qos_class(attr, QOS_CLASS_BACKGROUND, 0);
}
queue = dispatch_queue_create("com.moying.etrequest.cache", attr);
});
return queue;
}
@interface ETCacheSecure : NSObject <NSSecureCoding>
@property (nonatomic, assign) long long version;
@property (nonatomic, assign) NSStringEncoding stringEncoding;
@property (nonatomic, strong) NSDate *creationDate;
@property (nonatomic, strong) NSString *appVersionString;
@end
@implementation ETCacheSecure
+ (BOOL)supportsSecureCoding {
return YES;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super init])) {
self.version = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(version))] integerValue];
self.stringEncoding = [[aDecoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(stringEncoding))] integerValue];
self.creationDate = [aDecoder decodeObjectOfClass:[NSDate class] forKey:NSStringFromSelector(@selector(creationDate))];
self.appVersionString = [aDecoder decodeObjectOfClass:[NSString class] forKey:NSStringFromSelector(@selector(appVersionString))];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:@(self.version) forKey:NSStringFromSelector(@selector(version))];
[aCoder encodeObject:@(self.stringEncoding) forKey:NSStringFromSelector(@selector(stringEncoding))];
[aCoder encodeObject:self.creationDate forKey:NSStringFromSelector(@selector(creationDate))];
[aCoder encodeObject:self.appVersionString forKey:NSStringFromSelector(@selector(appVersionString))];
}
@end
@interface ETRequest ()
@property (nonatomic)ETCacheSecure * cacheSecure;
@property (nonatomic, strong) NSData *cacheData;
@property (nonatomic, strong) NSString *cacheString;
@property (nonatomic, strong) id cacheJSON;
@property (nonatomic, strong) NSXMLParser *cacheXML;
@property (nonatomic, assign) BOOL dataFromCache;
@end
@implementation ETRequest
- (void)start {
if (!self.ignoreCache) {
[self startWithoutCache];
return;
}
/// 恢复下载请求
if (self.resumableDownloadPath) {
[self startWithoutCache];
return;
}
if (![self loadCacheWithError:nil]) {
[self startWithoutCache];
return;
}
// 拿本地缓存
_dataFromCache = YES;
/// 直接结束
dispatch_async(dispatch_get_main_queue(), ^{
[self requestCompletePreprocessor];
[self requestCompleteFilter];
ETRequest *strongSelf = self;
[strongSelf.delegate requestFinished:strongSelf];
if (strongSelf.successCompletionBlock) {
strongSelf.successCompletionBlock(strongSelf);
}
[strongSelf clearCompletionBlock];
});
}
- (void)startWithoutCache {
[self clearCacheVariables];
[super start];
}
#pragma mark - Network Request Delegate
- (void)requestCompletePreprocessor {
[super requestCompletePreprocessor];
if (self.writeCacheAsynchronously) {
dispatch_async(etrequest_cache_writing_queue(), ^{
[self saveResponseDataToCacheFile:[super responseData]];
});
}else {
[self saveResponseDataToCacheFile:[super responseData]];
}
}
- (void)requestCompleteFilter {
}
- (void)requestFailedPreprocessor {
}
- (void)requestFailedFilter {
}
#pragma mark - Load Cache
#pragma mark - Subclass Override
- (NSInteger)cacheTimeInSeconds {
return -1;
}
- (long long)cacheVersion {
return 0;
}
- (id)cacheSensitiveData {
return nil;
}
- (BOOL)writeCacheAsynchronously {
return YES;
}
#pragma mark - Get
- (BOOL)isDataFromCache {
return _dataFromCache;
}
- (NSData *)responseData {
if (_cacheData) {
return _cacheData;
}
return [super responseData];
}
- (NSString *)responseString {
if (_cacheString) {
return _cacheString;
}
return [super responseString];
}
- (id)responseJSONObject {
if (_cacheJSON) {
return _cacheJSON;
}
return [super responseJSONObject];
}
- (id)responseObject {
if (_cacheJSON) {
return _cacheJSON;
}
if (_cacheXML) {
return _cacheXML;
}
if (_cacheData) {
return _cacheData;
}
return [super responseObject];
}
#pragma mark - Private
- (BOOL)loadCacheWithError:(NSError *__autoreleasing *)error {
if (self.cacheTimeInSeconds < 0) {
if (error) {
*error = [NSError errorWithDomain:ETRequestCacheErrorDomain code:ETRequestCacheErrorInvalidCacheTime userInfo:@{ NSLocalizedDescriptionKey:@"缓存已过期或者未找到缓存"}];
return NO;
}
}
if (![self loadCacheSecure]) {
if (error) {
*error = [NSError errorWithDomain:ETRequestCacheErrorDomain code:ETRequestCacheErrorInvalidMetadata userInfo:@{ NSLocalizedDescriptionKey:@"数据出错或者缓存不存在"}];
}
return NO;
}
return YES;
}
- (BOOL)validateCacheWithError:(NSError * _Nullable __autoreleasing *)error {
NSDate *creationDate = self.cacheSecure.creationDate;
NSTimeInterval duration = -[creationDate timeIntervalSinceNow];
if (duration < 0 || duration > [self cacheTimeInSeconds]) {
if (error) {
*error = [NSError errorWithDomain:ETRequestCacheErrorDomain code:ETRequestCacheErrorExpired userInfo:@{NSLocalizedDescriptionKey:@"缓存已过期"}];
}
return NO;
}
long long cacheVersionFileContent = self.cacheSecure.version;
if (cacheVersionFileContent != [self cacheVersion]) {
if (error) {
*error = [NSError errorWithDomain:ETRequestCacheErrorDomain code:ETRequestCacheErrorVersionMismatch userInfo:@{ NSLocalizedDescriptionKey:@"缓存版本不匹配"}];
}
return NO;
}
NSString *appVersionString = self.cacheSecure.appVersionString;
NSString *currentAppVersionString = [ETNetworkUtils appVersionString];
if (appVersionString || currentAppVersionString) {
if (appVersionString.length != currentAppVersionString.length || ![appVersionString isEqualToString:currentAppVersionString]) {
if (error) {
*error = [NSError errorWithDomain:ETRequestCacheErrorDomain code:ETRequestCacheErrorAppVersionMismatch userInfo:@{ NSLocalizedDescriptionKey:@"App版本与缓存数据版本不匹配"}];
}
return NO;
}
}
return YES;
}
// 加载 NSSecureCoding数据
- (BOOL)loadCacheSecure {
NSString *path = [self cacheMetadataFilePath];
NSFileManager * fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path isDirectory:nil]) {
@try {
_cacheSecure = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
return YES;
} @catch (NSException *exception) {
ETLog(@"加载元数据失败, 原因 = %@", exception.reason);
}
}
return NO;
}
- (void)saveResponseDataToCacheFile:(NSData *)data {
if ([self cacheTimeInSeconds] > 0 && ![self isDataFromCache]) {
if (data != nil) {
@try {
[data writeToFile:[self cacheFilePath] atomically:YES];
ETLog(@"缓存存储成功,地址 = %@", [self cacheFilePath]);
ETCacheSecure *metadata = [[ETCacheSecure alloc] init];
metadata.version = [self cacheVersion];
metadata.stringEncoding = [ETNetworkUtils stringEncodingWithRequest:self];
metadata.creationDate = [NSDate date];
metadata.appVersionString = [ETNetworkUtils appVersionString];
[NSKeyedArchiver archiveRootObject:metadata toFile:[self cacheMetadataFilePath]];
} @catch (NSException *exception) {
ETLog(@"缓存存储失败,原因 = %@", exception.reason);
}
}
}
}
- (NSString*)cacheMetadataFilePath {
//path + filename
NSString *cacheMetadataFileName = [NSString stringWithFormat:@"%@.metadata", [self cacheFileName]];
NSString *path = [self cacheBasePath];
path = [path stringByAppendingPathComponent:cacheMetadataFileName];
return path;
}
- (NSString*)cacheFileName {
NSString *requestUrl = [self requestUrl];
NSString *baseUrl = [ETNetworkConfig sharedConfig].baseUrl;
id argument = [self cacheFileNameFilterForRequestArgument:[self requestArgument]];
NSString *requestInfo = [NSString stringWithFormat:@"Method:%ld Host:%@ Url:%@ Argument:%@",(unsigned long)[self requestMethod],baseUrl,requestUrl,argument];
NSString *fileName = [ETNetworkUtils md5StringFromString:requestInfo];
return fileName;
}
- (NSString*)cacheFilePath {
NSString *cacheFileName = [self cacheFileName];
NSString *path = [self cacheBasePath];
path = [path stringByAppendingPathComponent:cacheFileName];
return path;
}
// 缓存的基础地址
- (NSString*)cacheBasePath {
NSString *pathOfLibrary = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [pathOfLibrary stringByAppendingPathComponent:@"ETLazyRequestCache"];
// 过滤缓存地址
NSArray<id<ETCacheDirPathFilterProtocol>> * cacheFilter = [[ETNetworkConfig sharedConfig] cacheDirPathFilters];
if (cacheFilter.count > 0) {
for (id<ETCacheDirPathFilterProtocol>f in cacheFilter) {
path = [f filterCacheDirPath:path withRequest:self];
}
}
/// 创建文件
[self createDirectoryIfNeeded:path];
return path;
}
- (void)clearCacheVariables {
_cacheData = nil;
_cacheString = nil;
_cacheXML = nil;
_cacheJSON = nil;
_cacheSecure = nil;
}
#pragma mark - 创建缓存目录
/// 如果该目录不存在就创建该目录
/// 如果路径格式不正确则重新创建
- (void)createDirectoryIfNeeded:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) {
[self createBaseDirectoryAtPath:path];
} else {
if (!isDir) {
NSError *error = nil;
[fileManager removeItemAtPath:path error:&error];
[self createBaseDirectoryAtPath:path];
}
}
}
- (void)createBaseDirectoryAtPath:(NSString*)path {
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES
attributes:nil error:&error];
if (error) {
ETLog(@"创建缓存目录失败, error = %@", error);
} else {
[ETNetworkUtils addDoNotBackupAttribute:path];
}
}
@end