-
Notifications
You must be signed in to change notification settings - Fork 5
/
Tin.m
560 lines (432 loc) · 20.6 KB
/
Tin.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//
// Tin.m
// TouchPoint
//
// Created by Piet Jaspers on 10/06/11.
// Copyright 2011 10to1. All rights reserved.
//
#import "Tin.h"
// Since ASIHTTP is no longer maintained, we switched to [AFNetworking](https://github.com/AFNetworking/AFNetworking)
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperation.h"
// Each request returns a [TinResponse](TinResponse.html)
#import "TinBasicAuthenticator.h"
#import "TinResponse.h"
#import "TinFile.h"
#import "TinHTTPRequestOperation.h"
// Contains additions to default objects to aid Tin
#import "Tin+Extensions.h"
@interface Tin (URL)
- (NSString *)normalizeURL:(NSString *)aURL withQuery:(id)query;
- (NSString *)prependHTTPtoURL:(NSString *)aUrl;
- (NSString *)normalizeQuery:(id)query;
@end
@interface Tin (Authorization)
- (void)setOptionsOnClient:(AFHTTPClient *)request;
- (void)setOptionsOnRequest:(NSMutableURLRequest *)request;
@end
@interface Tin (Blocks)
- (void)waitFor:(void(^)(void(^endCallback)(void)))block;
@end
@interface Tin (Requests)
- (NSArray*)buildRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andFiles:(NSMutableDictionary *)files;
- (TinResponse *)performSynchronousRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andFiles:(NSMutableDictionary *)files;
- (TinResponse *)performSynchronousRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body;
- (void)performRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andSuccessCallback:(void(^)(TinResponse *response))returnSuccess;
- (void)performRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andFiles:(NSMutableDictionary *)files andSuccessCallback:(void(^)(TinResponse *response))returnSuccess;
@end
@implementation Tin
@synthesize baseURI;
@synthesize authenticator = _authenticator;
@synthesize timeoutSeconds;
@synthesize contentType;
@synthesize accept = _accept;
@synthesize headers;
@synthesize debugOutput;
@synthesize delegate = _delegate;
#pragma mark - Class methods
#pragma mark GET ASYNCHRONOUS
// ## `GET` requests
//
// Methods for use with `GET` requests.
//
// [Tin get:@"http://url.com/" success:(NSDictionary *data) { NSLog(@"Response %@", data)}];
//
+ (void)get:(NSString *)url success:(void(^)(TinResponse *response))callback {
[self get:url query:nil success:callback];
}
+ (void)get:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[[[self alloc] init] get:url query:query success:callback];
}
#pragma mark GET SYNCHRONOUS
+ (TinResponse *)get:(NSString *)url{
return [self get:url query:nil];
}
+ (TinResponse *)get:(NSString *)url query:(id)query {
return [[[self alloc] init] get:url query:query];
}
#pragma mark POST ASYNCHRONOUS
// ## `POST` requests
//
// Methods for use with `POST` requests.
//
// [Tin post:@"http://url.com/"
// query:[NSDictionary dictionaryWithObjectsAndKeys:@"string", @"key", nil]
// success:nil
// error:nil];
//
+ (void)post:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self post:url query:query body:nil success:callback];
}
+ (void)post:(NSString *)url body:(id)body success:(void(^)(TinResponse *response))callback {
[self post:url query:nil body:body success:callback];
}
+ (void)post:(NSString *)url query:(id)query body:(id)body success:(void(^)(TinResponse *response))callback {
[self post:url query:query body:body files:nil success:callback];
}
+ (void)post:(NSString *)url query:(id)aQuery body:(NSDictionary *)bodyData files:(NSMutableDictionary *)files success:(void(^)(TinResponse *response))callback {
[[[self alloc] init] post:url query:aQuery body:bodyData files:files success:callback];
}
#pragma mark POST SYNCHRONOUS
+ (TinResponse *)post:(NSString *)url query:(id)aQuery{
return [self post:url query:aQuery body:nil];
}
+ (TinResponse *)post:(NSString *)url body:(NSDictionary *)bodyData{
return [self post:url query:nil body:bodyData];
}
+ (TinResponse *)post:(NSString *)url query:(id)aQuery body:(NSDictionary *)bodyData {
return [[[self alloc] init] post:url query:aQuery body:bodyData files:nil];
}
+ (TinResponse *)post:(NSString *)url query:(id)aQuery body:(NSDictionary *)bodyData files:(NSMutableDictionary *)files {
return [[[self alloc] init] post:url query:aQuery body:bodyData files:files];
}
#pragma mark PUT ASYNCHRONOUS
// ## `PUT` requests
//
// Methods for use with `PUT` requests.
//
// [Tin put:@"http://url.com/"
// body:[NSString stringWithFormat:@"user=%@", @"Jake"]
// success:nil
// error:nil];
//
+ (void)put:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self put:url query:query body:nil success:callback];
}
+ (void)put:(NSString *)url body:(id)body success:(void(^)(TinResponse *response))callback {
[self put:url query:nil body:body success:callback];
}
+ (void)put:(NSString *)url query:(id)query body:(id)body success:(void(^)(TinResponse *response))callback {
[self put:url query:query body:body files:nil success:callback];
}
+ (void)put:(NSString *)url query:(id)aQuery body:(id)body files:(NSMutableDictionary *)files success:(void(^)(TinResponse *response))callback {
[[[self alloc] init] put:url query:aQuery body:body files:files success:callback];
}
#pragma mark PUT SYNCHRONOUS
+ (TinResponse *)put:(NSString *)url query:(id)aQuery{
return [self put:url query:aQuery body:nil];
}
+ (TinResponse *)put:(NSString *)url body:(id)body {
return [self put:url query:nil body:body];
}
+ (TinResponse *)put:(NSString *)url query:(id)aQuery body:(id)body {
return [self put:url query:aQuery body:body files:nil];
}
+ (TinResponse *)put:(NSString *)url query:(id)aQuery body:(id)body files:(NSMutableDictionary *)files {
return [[[self alloc] init] put:url query:aQuery body:body files:files];
}
#pragma mark DELETE ASYNCHRONOUS
+ (void)delete:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self delete:url query:query body:nil success:callback];
}
+ (void)delete:(NSString *)url body:(id)body success:(void(^)(TinResponse *response))callback {
[self delete:url query:nil body:body success:callback];
}
+ (void)delete:(NSString *)url query:(id)query body:(id)body success:(void(^)(TinResponse *response))callback {
[[[self alloc] init] delete:url query:query body:body success:callback];
}
#pragma mark DELETE SYNCHRONOUS
+ (TinResponse *)delete:(NSString *)url query:(id)aQuery{
return [self delete:url query:aQuery body:nil];
}
+ (TinResponse *)delete:(NSString *)url body:(id)body {
return [self delete:url query:nil body:body];
}
+ (TinResponse *)delete:(NSString *)url query:(id)aQuery body:(id)body {
return [[[self alloc] init] delete:url query:aQuery body:body];
}
#pragma mark - Instance Methods
#pragma mark - initialisation & dealloc
- (id)init {
if ((self = [super init])) {
_bodyParameterEncoding = TinJSONParameterEncoding;
}
return self;
}
- (void)dealloc {
self.authenticator = nil;
self.baseURI = nil;
self.contentType = nil;
self.headers = nil;
}
#pragma mark GET ASYNCHRONOUS
- (void)get:(NSString *)url success:(void(^)(TinResponse *response))callback {
[self get:url query:nil success:callback];
}
- (void)get:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self performRequest:@"GET" withURL:url andQuery:query andBody:nil andSuccessCallback:callback];
}
#pragma mark GET SYNCHRONOUS
- (TinResponse *)get:(NSString *)url {
return [self get:url query:nil];
}
- (TinResponse *)get:(NSString *)url query:(id)query {
return [self performSynchronousRequest:@"GET" withURL:url andQuery:query andBody:nil];
}
- (NSURLRequest*)requestGet:(NSString *)url query:(id)query {
return [[self buildRequest:@"GET" withURL:url andQuery:query andBody:nil andFiles:nil] objectAtIndex:1];
}
#pragma mark POST ASYNCHRONOUS
- (void)post:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self post:url query:query body:nil success:callback];
}
- (void)post:(NSString *)url body:(id)bodyData success:(void(^)(TinResponse *response))callback {
[self post:url query:nil body:bodyData success:callback];
}
- (void)post:(NSString *)url query:(id)query body:(id)bodyData success:(void(^)(TinResponse *response))callback {
[self post:url query:query body:bodyData files:nil success:callback];
}
- (void)post:(NSString *)url query:(id)query body:(id)bodyData files:(NSMutableDictionary *)files success:(void(^)(TinResponse *response))callback {
[self performRequest:@"POST" withURL:url andQuery:query andBody:bodyData andFiles:files andSuccessCallback:callback];
}
#pragma mark POST SYNCHRONOUS
- (TinResponse *)post:(NSString *)url body:(NSDictionary *)bodyData {
return [self post:url query:nil body:bodyData];
}
- (TinResponse *)post:(NSString *)url query:(id)aQuery {
return [self post:url query:aQuery body:nil];
}
- (TinResponse *)post:(NSString *)url query:(id)aQuery body:(NSDictionary *)bodyData {
return [self post:url query:aQuery body:bodyData files:nil];
}
- (TinResponse *)post:(NSString *)url query:(id)aQuery body:(NSDictionary *)bodyData files:(NSMutableDictionary *)files {
return [self performSynchronousRequest:@"POST" withURL:url andQuery:aQuery andBody:bodyData andFiles:files];
}
- (NSURLRequest*)requestPost:(NSString *)url query:(id)aQuery body:(NSDictionary *)bodyData files:(NSMutableDictionary *)files {
return [[self buildRequest:@"POST" withURL:url andQuery:aQuery andBody:bodyData andFiles:files] objectAtIndex:1];
}
#pragma mark PUT ASYNCHRONOUS
- (void)put:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self put:url query:query body:nil success:callback];
}
- (void)put:(NSString *)url body:(id)body success:(void(^)(TinResponse *response))callback {
[self put:url query:nil body:body success:callback];
}
- (void)put:(NSString *)url query:(id)query body:(id)body success:(void(^)(TinResponse *response))callback{
[self put:url query:query body:body files:nil success:callback];
}
- (void)put:(NSString *)url query:(id)query body:(id)body files:(NSMutableDictionary *)files success:(void(^)(TinResponse *response))callback {
[self performRequest:@"PUT" withURL:url andQuery:query andBody:body andFiles:files andSuccessCallback:callback];
}
#pragma mark PUT SYNCHRONOUS
- (TinResponse *)put:(NSString *)url query:(id)aQuery{
return [self put:url query:aQuery body:nil];
}
- (TinResponse *)put:(NSString *)url body:(id)body{
return [self put:url query:nil body:body];
}
- (TinResponse *)put:(NSString *)url query:(id)aQuery body:(id)body {
return [self put:url query:aQuery body:body files:nil];
}
- (TinResponse *)put:(NSString *)url query:(id)aQuery body:(id)body files:(NSMutableDictionary *)files {
return [self performSynchronousRequest:@"PUT" withURL:url andQuery:aQuery andBody:body andFiles:files];
}
- (NSURLRequest *)requestPut:(NSString *)url query:(id)aQuery body:(id)body files:(NSMutableDictionary *)files {
return [[self buildRequest:@"PUT" withURL:url andQuery:aQuery andBody:body andFiles:files] objectAtIndex:1];
}
#pragma mark DELETE ASYNCHRONOUS
- (void)delete:(NSString *)url query:(id)query success:(void(^)(TinResponse *response))callback {
[self delete:url query:query body:nil success:callback];
}
- (void)delete:(NSString *)url body:(id)body success:(void(^)(TinResponse *response))callback {
[self delete:url query:nil body:body success:callback];
}
- (void)delete:(NSString *)url query:(id)query body:(id)body success:(void(^)(TinResponse *response))callback{
[self performRequest:@"DELETE" withURL:url andQuery:query andBody:body andFiles:nil andSuccessCallback:callback];
}
#pragma mark DELETE SYNCHRONOUS
- (TinResponse *)delete:(NSString *)url query:(id)aQuery{
return [self delete:url query:aQuery body:nil];
}
- (TinResponse *)delete:(NSString *)url body:(id)body{
return [self delete:url query:nil body:body];
}
- (TinResponse *)delete:(NSString *)url query:(id)aQuery body:(id)body {
return [self performSynchronousRequest:@"DELETE" withURL:url andQuery:aQuery andBody:body andFiles:nil];
}
- (NSURLRequest*)requestDelete:(NSString *)url query:(id)aQuery body:(id)body {
return [[self buildRequest:@"DELETE" withURL:url andQuery:aQuery andBody:body andFiles:nil] objectAtIndex:1];
}
#pragma mark - Synchronous requests
- (TinResponse *)performSynchronousRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body {
return [self performSynchronousRequest:method withURL:urlString andQuery:query andBody:body andFiles:nil];
}
- (TinResponse *)performSynchronousRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andFiles:(NSMutableDictionary *)files {
__block TinResponse *synchronousRequest = nil;
[self waitFor:^(void(^done)(void)) {
[self performRequest:method withURL:urlString andQuery:query andBody:body andFiles:files andSuccessCallback:^(TinResponse *response) {
synchronousRequest = response;
done();
}];
}];
return synchronousRequest;
}
#pragma mark - Asynchronous requests
- (void)performRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andSuccessCallback:(void(^)(TinResponse *response))returnSuccess {
[self performRequest:method withURL:urlString andQuery:query andBody:body andFiles:nil andSuccessCallback:returnSuccess];
}
- (NSArray*)buildRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andFiles:(NSMutableDictionary *)files {
// Initialize client
AFHTTPClient *_client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:self.baseURI ?: @"http://localhost"]];
[self setOptionsOnClient:_client];
if (body && self.contentType != nil && ![self.contentType isEqualToString:@""]) {
[_client setDefaultHeader:@"Content-Type" value:self.contentType];
}
if (self.accept) {
[_client setDefaultHeader:@"Accept" value:self.accept];
}
query = [self normalizeQuery:query];
if ([self.authenticator respondsToSelector:@selector(tin:applyAuthenticationOnClient:withMethod:url:query:)])
query = [self.authenticator tin:self applyAuthenticationOnClient:_client withMethod:method url:urlString query:query];
// Initialize request
NSString *_url = [self normalizeURL:urlString withQuery:query];
if (self.debugOutput) NSLog(@"Making request to: %@", _url);
NSMutableURLRequest *_request;
if (files) {
_request = [_client multipartFormRequestWithMethod:method path:_url parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[files enumerateKeysAndObjectsUsingBlock:^(id attribute_name, TinFile *file, BOOL *stop) {
[formData appendPartWithFileData:file.data name:attribute_name fileName:file.name mimeType:file.mimeType];
}];
}];
} else {
_request = [_client requestWithMethod:method path:_url parameters:body];
}
[self setOptionsOnRequest:_request];
return [NSArray arrayWithObjects:_client, _request, nil];
}
- (void)performRequest:(NSString *)method withURL:(NSString *)urlString andQuery:(id)query andBody:(id)body andFiles:(NSMutableDictionary *)files andSuccessCallback:(void(^)(TinResponse *response))returnSuccess {
NSArray* req = [self buildRequest:method withURL:urlString andQuery:query andBody:body andFiles:files];
NSURLRequest* _request = [req objectAtIndex:1];
// Initialize operation
TinHTTPRequestOperation *_operation = [[TinHTTPRequestOperation alloc] initWithRequest:_request] ;
if (files) {
[_operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
if ([self.delegate respondsToSelector:@selector(didProgressRequest:totalBytesWriten:totalBytesExpectedToWrite:)]) {
[self.delegate didProgressRequest:_request totalBytesWriten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
}];
}
[_operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (self.debugOutput) NSLog(@"\t Request succesfull");
NSError *_error = nil;
TinResponse *_response = [TinResponse responseWithOperation:operation body:responseObject error:_error];
if ([self.delegate respondsToSelector:@selector(didEndRequest:withResponse:)]) {
[self.delegate didEndRequest:operation.request withResponse:_response];
}
if (returnSuccess) {
returnSuccess(_response);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.debugOutput) NSLog(@"\t Request failed, error: %@", error);
TinResponse *_response = [TinResponse responseWithOperation:operation body:nil error:error];
if ([self.delegate respondsToSelector:@selector(didEndRequest:withResponse:)]) {
[self.delegate didEndRequest:operation.request withResponse:_response];
}
if (returnSuccess) {
returnSuccess(_response);
}
}];
if ([self.delegate respondsToSelector:@selector(willBeginRequest:)]) {
[self.delegate willBeginRequest:_request];
}
[_operation start];
}
#pragma mark - Utility
// Sets all specified options to the request
- (void)setOptionsOnClient:(AFHTTPClient *)client {
if (self.headers) {
[self.headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[client setDefaultHeader:key value:obj];
}];
}
client.parameterEncoding = _bodyParameterEncoding;
}
// Sets all specified options to the request
- (void)setOptionsOnRequest:(NSMutableURLRequest *)request {
request.HTTPShouldHandleCookies = NO;
if (self.timeoutSeconds) {
[request setTimeoutInterval:self.timeoutSeconds];
}
}
#pragma mark - URL helpers
// Creates the `URL` which will be used in the actual request.
- (NSString *)normalizeURL:(NSString *)aURL withQuery:(id) query {
NSString *urlString = aURL;
// Adds the query
if (query) urlString = [NSString stringWithFormat:@"%@%@", urlString, [self normalizeQuery:query]];
return urlString;
}
- (NSString *)normalizeQuery:(id)query {
if ([query isKindOfClass:[NSString class]]) {
if ([query length] > 0 && [query characterAtIndex:0] != '?')
query = [NSString stringWithFormat:@"?%@", query];
return query;
}
if ([query isKindOfClass:[NSDictionary class]])
return [(NSDictionary *) query toQueryString];
return nil;
}
+ (NSDictionary*)splitQuery:(id)query
{
if (!query) return nil;
if ([query isKindOfClass:[NSDictionary class]]) return query;
if ([query isKindOfClass:[NSArray class]]) return query;
if ([query isKindOfClass:[NSData class]])
query = [[NSString alloc] initWithData:query encoding:NSUTF8StringEncoding];
// make sure we have a string
query = [query description];
// Decode the parameters given in the query string, and add their encoded counterparts
if ([query length] > 0 && [query characterAtIndex:0] == '?')
query = [query substringFromIndex:1];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
NSArray *pairs = [query componentsSeparatedByString:@"&"];
for (NSString *pair in pairs) {
NSString *key, *value;
NSRange separator = [pair rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"="]];
if (separator.location != NSNotFound) {
key = [self decodeFromURL:[pair substringToIndex:separator.location]];
value = [self decodeFromURL:[pair substringFromIndex:separator.location + 1]];
} else {
key = [self decodeFromURL:pair];
value = @"";
}
if (key && key.length > 0) {
[result setObject:value forKey:key];
}
}
return result;
}
+ (NSString *)decodeFromURL:(NSString*)source
{
NSString *decoded = (__bridge_transfer NSString*) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)source, CFSTR(""), kCFStringEncodingUTF8);
return [decoded stringByReplacingOccurrencesOfString:@"+" withString:@" "];
}
#pragma mark - Synchronous helper
- (void)waitFor:(void(^)(void(^endCallback)(void)))block {
dispatch_semaphore_t waiter = dispatch_semaphore_create(0);
block(^{
dispatch_semaphore_signal(waiter);
});
dispatch_semaphore_wait(waiter, DISPATCH_TIME_FOREVER);
}
@end