-
Notifications
You must be signed in to change notification settings - Fork 0
/
GMImageManager.m
100 lines (80 loc) · 2.84 KB
/
GMImageManager.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
//
// GMImageManager.m
//
// Created by Gersham Meharg on 11-02-18.
// Copyright 2011 Gersham Meharg. All rights reserved.
//
#import "GMImageManager.h"
#import "GMImageUploadOperation.h"
#import "GMImageUploadOperationResult.h"
#import "NSString+URLEncode.h"
@implementation GMImageManager
static GMImageManager *shared = nil;
NSString *const ImageUploadCompleteNotification = @"ImageUploadCompleteNotification";
NSString *const ImageUploadFailedNotification = @"ImageUploadFailedNotification";
@synthesize uploadQueue;
@synthesize downloadQueue = _downloadQueue;
@synthesize pendingImageDownloads = _pendingImageDownloads;
@synthesize apiEndpoint = _apiEndpoint;
- (void)uploadImage:(UIImage *)image
path:(NSString *)path
parameters:(NSDictionary *)parameters
completion:(void (^)(GMImageUploadOperationResult *result))completion {
// Build URL
NSString *location;
if (parameters.count > 0) {
NSMutableString *args = [NSMutableString stringWithString:@"?"];
for (NSString *key in parameters) {
if ([parameters objectForKey:key] == [NSNull null]) {
DLog(@"Null value for %@ skipping", key);
continue;
}
NSString *value = [[parameters objectForKey:key] urlEncodedString];
[args appendString:[NSString stringWithFormat:@"%@=%@&", key, value]];
}
location = [NSString stringWithFormat:@"%@%@%@", _apiEndpoint, path, [args substringWithRange:NSMakeRange(0, args.length-1)]];
} else {
location = [NSString stringWithFormat:@"%@%@", _apiEndpoint, path];
}
NSURL *url = [[NSURL alloc] initWithString:location];
[self uploadImage:image url:url completion:completion];
}
- (void)uploadImage:(UIImage *)image
url:(NSURL *)url
completion:(void (^)(GMImageUploadOperationResult *result))completion {
NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.5)];
// Do Operation
if (url != nil) {
GMImageUploadOperation *op = [GMImageUploadOperation new];
op.url = url;
op.completion = completion;
op.delegate = self;
op.data = data;
[self.uploadQueue addOperation:op];
} else {
NSLog(@"Not performing network operation for undefined url");
}
}
- (void)uploadResult:(GMOperationResult *)result {
OperationCallbackBlock block = (OperationCallbackBlock)result.completion;
block(result);
}
#pragma mark Singleton
+ (id)shared {
@synchronized(self) {
if(shared == nil)
shared = [[super allocWithZone:NULL] init];
}
return shared;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self shared];
}
- (id)init {
if ((self = [super init])) {
self.uploadQueue = [[NSOperationQueue alloc] init];
[self.uploadQueue setMaxConcurrentOperationCount:1];
}
return self;
}
@end