-
Notifications
You must be signed in to change notification settings - Fork 0
/
Telemachus.m
66 lines (51 loc) · 1.67 KB
/
Telemachus.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
//
// Telemachus.m
// Telemachus
//
// Created by Aaron Vegh on 2015-07-09.
// Copyright © 2015 Aaron Vegh. All rights reserved.
//
#import "Telemachus.h"
#import "XImage.h"
@interface Telemachus ()
@property (readwrite, strong) NSCache * imageCache;
@property (readwrite, strong) NSURLSession * urlSession;
@end
@implementation Telemachus
+ (Telemachus *)sharedInstance
{
static Telemachus * sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Telemachus alloc] init];
});
return sharedInstance;
}
- (instancetype)init
{
self = [super init];
self.imageCache = [NSCache new];
self.urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
return self;
}
- (void)getImage:(NSString*)urlString completion:(void (^)(XImage * image))completion
{
// check the cache in case we already have this
if ([self.imageCache objectForKey:urlString]) {
completion([self.imageCache objectForKey:urlString]);
}
else {
NSURL * theURL = [NSURL URLWithString:urlString];
if (theURL) {
NSURLSessionDataTask * dataTask = [self.urlSession dataTaskWithURL:theURL completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {
XImage * newImage = [[XImage alloc] initWithData:data];
if (newImage) {
[self.imageCache setObject:newImage forKey:urlString];
completion(newImage);
}
}];
[dataTask resume];
}
}
}
@end