forked from tanhaogg/THWebService
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTHWebDataCache.m
More file actions
103 lines (92 loc) · 2.55 KB
/
THWebDataCache.m
File metadata and controls
103 lines (92 loc) · 2.55 KB
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
//
// THWebDataCache.m
// THWebServiceTest
//
// Created by Hao Tan on 12-4-12.
// Copyright (c) 2012年 http://www.tanhao.me. All rights reserved.
//
#import "THWebDataCache.h"
#import "THWebDefine.h"
@implementation THWebDataCache
- (id)initWithSubDirectory:(NSString *)subDirectory
{
self = [super init];
if (self)
{
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
if ([cachePaths count] == 0)
{
return nil;
}
NSString *rootCachePath = [[cachePaths objectAtIndex:0] stringByAppendingPathComponent:kTHWebDataCacheDirectory];
cacheDirectory = [rootCachePath stringByAppendingPathComponent:subDirectory];
if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory])
{
BOOL sucess = [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:NULL];
if (!sucess)
{
return nil;
}
}
}
return self;
}
- (id)init
{
return [self initWithSubDirectory:@""];
}
- (NSString *)cachePathForKey:(NSString *)key
{
return [THWebUtility hashString:key with:THHashKindMd5];
}
- (BOOL)storeData:(NSData *)aData forKey:(NSString *)key
{
if (!aData || [key length] ==0)
{
return NO;
}
NSString *fileName = [self cachePathForKey:key];
if ([fileName length] == 0)
{
return NO;
}
NSString *filePath = [cacheDirectory stringByAppendingPathComponent:fileName];
return [aData writeToFile:filePath atomically:YES];
}
- (NSData *)dataFromKey:(NSString *)key
{
if ([key length] ==0)
{
return nil;
}
NSString *fileName = [self cachePathForKey:key];
if ([fileName length] == 0)
{
return nil;
}
NSString *filePath = [cacheDirectory stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
return nil;
}
return [NSData dataWithContentsOfFile:filePath];
}
- (BOOL)removeDataForKey:(NSString *)key
{
if ([key length] ==0)
{
return NO;
}
NSString *fileName = [self cachePathForKey:key];
if ([fileName length] == 0)
{
return NO;
}
NSString *filePath = [cacheDirectory stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
return YES;
}
return [[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
}
@end