-
Notifications
You must be signed in to change notification settings - Fork 4
/
UTOfflineCache.m
101 lines (81 loc) · 2.67 KB
/
UTOfflineCache.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
//
// UTOfflineCache.m
// RingFinder
//
// Created by Danny Morrow on 1/29/13.
// Copyright (c) 2013 unitytheory. All rights reserved.
//
#import "UTOfflineCache.h"
#import "NSStringAdditions.h"
static UTOfflineCache *sharedInstance = nil;
@implementation UTOfflineCache
+ (UTOfflineCache *) sharedCache
{
static dispatch_once_t onceQueue;
dispatch_once(&onceQueue, ^{
sharedInstance = [[UTOfflineCache alloc] init];
[sharedInstance setStoragePath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"UTOfflineCache"]];
});
return sharedInstance;
}
- (NSString *)storagePath
{
return _storagePath;
}
- (void)setStoragePath:(NSString *)path
{
_storagePath = path;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (exists && !isDirectory)
{
[NSException raise:@"FileExistsAtCachePath" format:@"Cannot create a directory for the cache at '%@', because a file already exists",path];
}
else if (!exists)
{
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
if (![fileManager fileExistsAtPath:path])
{
[NSException raise:@"FailedToCreateCacheDirectory" format:@"Failed to create a directory for the cache at '%@'",path];
}
}
}
- (void)storeData:(NSData*)data fromURL:(NSURL*) url
{
if (data)
{
NSString *dataPath = [self pathToDataForURL:url];
NSError* error;
[data writeToFile:dataPath options:NSDataWritingAtomic error:&error];
}
}
- (void) removeCachedDataForURL:(NSURL *)url
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString* path = [self pathToDataForURL:url];
if (path) [fileManager removeItemAtPath:path error:NULL];
}
- (NSData*) cachedDataForURL:(NSURL *)url
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString* path = [self pathToDataForURL:url];
if (path) return [fileManager contentsAtPath:path];
return nil;
}
- (BOOL) hasCachedDataForURL:(NSURL *)url
{
return [[NSFileManager defaultManager] fileExistsAtPath:[self pathToDataForURL:url]];
}
- (NSString *)pathToDataForURL:(NSURL *)url
{
NSString *extension = [[url path] pathExtension];
NSString *name = [[self class] keyForURL:url];
if (extension.length) name = [name stringByAppendingPathExtension:extension];
return [[self storagePath] stringByAppendingPathComponent: name];
}
+ (NSString *) keyForURL:(NSURL*)url
{
return [url.absoluteString md5HexDigest];
}
@end