-
Notifications
You must be signed in to change notification settings - Fork 6
/
MVFileUpload.m
248 lines (213 loc) · 8.23 KB
/
MVFileUpload.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
#import "MVFileUpload.h"
#import "MVUploadAuthorization.h"
#import "MVFileUpload_Private.h"
#define kMVFileUploadSuccessStatusCode 200
@interface MVFileUpload ()
- (void)addValue:(NSString*)value
forKey:(NSString*)aKey
toPostBody:(NSMutableData*)postBody
stringBoundary:(NSString*)stringBoundary;
@end
@implementation MVFileUpload
@synthesize key = key_,
data = data_,
operationQueue = operationQueue_,
urlConnection = urlConnection_,
mutableData = mutableData_,
statusCode = statusCode_,
uploadAuthorization = uploadAuthorization_,
uploadPercentage = uploadPercentage_,
finished = finished_,
error = error_,
remoteURL = remoteURL_,
remoteURLForAsset = remoteURLForAsset_,
delegate = delegate_;
- (id)initWithKey:(NSString*)key
data:(NSData*)data
operationQueue:(NSOperationQueue*)operationQueue
uploadAuthorization:(MVUploadAuthorization*)uploadAuthorization
{
self = [super init];
if(self)
{
key_ = key;
data_ = data;
operationQueue_ = operationQueue;
urlConnection_ = nil;
mutableData_ = nil;
statusCode_ = -1;
uploadAuthorization_ = uploadAuthorization;
uploadPercentage_ = 0;
finished_ = NO;
error_ = NO;
remoteURL_ = nil;
remoteURLForAsset_ = nil;
delegate_ = nil;
}
return self;
}
- (void)start
{
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
if([self.delegate respondsToSelector:@selector(fileUploadShouldStart:)])
{
if(![self.delegate fileUploadShouldStart:self])
return;
}
/*
* Init URL connection and start uploading the file
*/
NSURL *url = [NSURL URLWithString:self.uploadAuthorization.uploadURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
//Add the header info
NSString *stringBoundary = @"0xKhTmLbOuNdArY";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",
stringBoundary];
[req addValue:contentType forHTTPHeaderField:@"Content-Type"];
// create the body
NSMutableData *postBody = [NSMutableData data];
// add key
[self addValue:self.key
forKey:@"key"
toPostBody:postBody
stringBoundary:stringBoundary];
[self addValue:self.uploadAuthorization.successActionRedirect
forKey:@"success_action_redirect"
toPostBody:postBody
stringBoundary:stringBoundary];
[self addValue:self.uploadAuthorization.policy
forKey:@"policy"
toPostBody:postBody
stringBoundary:stringBoundary];
[self addValue:self.uploadAuthorization.signature
forKey:@"signature"
toPostBody:postBody
stringBoundary:stringBoundary];
[self addValue:self.uploadAuthorization.accessKeyId
forKey:@"AWSAccessKeyId"
toPostBody:postBody
stringBoundary:stringBoundary];
[self addValue:self.uploadAuthorization.acl
forKey:@"acl"
toPostBody:postBody
stringBoundary:stringBoundary];
// append file data
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary]
dataUsingEncoding:NSUTF8StringEncoding]];
NSString *line = [NSString stringWithFormat:@"Content-Disposition: form-data; \
name=\"file\"; filename=\"%@\"\r\n",[self.key lastPathComponent]];
[postBody appendData:[line dataUsingEncoding:NSUTF8StringEncoding]];
line = @"Content-Type: application/octet-stream\r\n";
[postBody appendData:[line dataUsingEncoding:NSASCIIStringEncoding]];
line = @"Content-Transfer-Encoding: binary\r\n\r\n";
[postBody appendData:[line dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:self.data];
line = [NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary];
[postBody appendData:[line dataUsingEncoding:NSUTF8StringEncoding]];
//add the body to the post
[req setHTTPBody:postBody];
self.mutableData = [NSMutableData data];
self.urlConnection = [NSURLConnection connectionWithRequest:req
delegate:self];
if (!self.urlConnection)
{
dispatch_async(dispatch_get_main_queue(), ^{
if([self.delegate respondsToSelector:@selector(fileUpload:didFailWithError:)])
[self.delegate fileUpload:self didFailWithError:nil];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
if([self.delegate respondsToSelector:@selector(fileUploadDidStart:)])
[self.delegate fileUploadDidStart:self];
});
CFRunLoopRun();
}
}];
[self.operationQueue addOperation:operation];
}
#pragma mark -
#pragma mark Private Methods
- (void)addValue:(NSString*)value
forKey:(NSString*)aKey
toPostBody:(NSMutableData*)postBody
stringBoundary:(NSString*)stringBoundary
{
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; \
name=\"%@\"\r\n\r\n",aKey] dataUsingEncoding:NSASCIIStringEncoding]];
[postBody appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
#pragma mark -
#pragma mark NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
if([self.delegate respondsToSelector:@selector(fileUpload:didFailWithError:)])
[self.delegate fileUpload:self didFailWithError:error];
self.error = YES;
});
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.mutableData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
float percent = (100*(float)totalBytesWritten/(float)totalBytesExpectedToWrite);
self.uploadPercentage = percent;
dispatch_async(dispatch_get_main_queue(), ^{
if([self.delegate respondsToSelector:@selector(fileUpload:didProgress:)])
[self.delegate fileUpload:self didProgress:percent];
});
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
self.statusCode = [httpResponse statusCode];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
NSObject *json = [NSJSONSerialization JSONObjectWithData:self.mutableData
options:0
error:&error];
if(self.statusCode == kMVFileUploadSuccessStatusCode && !error)
{
NSString *hrefString = [json valueForKey:@"href"];
self.remoteURLForAsset = self.remoteURL = [NSURL URLWithString:hrefString];
if(self.uploadPercentage != 100)
{
self.uploadPercentage = 100;
}
self.finished = YES;
dispatch_async(dispatch_get_main_queue(), ^{
if([self.delegate respondsToSelector:@selector(fileUploadDidFinish:)])
[self.delegate fileUploadDidFinish:self];
});
}
else
{
NSError *error = [NSError errorWithDomain:[NSString stringWithFormat:
@"StatusCode (%li) should be %i",
(long)(self.statusCode),
kMVFileUploadSuccessStatusCode]
code:self.statusCode
userInfo:nil];
dispatch_async(dispatch_get_main_queue(), ^{
if([self.delegate respondsToSelector:@selector(fileUpload:didFailWithError:)])
[self.delegate fileUpload:self didFailWithError:error];
self.error = YES;
});
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
@end