-
Notifications
You must be signed in to change notification settings - Fork 1
/
AFRESTClient.m
417 lines (331 loc) · 16.1 KB
/
AFRESTClient.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
// AFRESTClient.m
//
// Copyright (c) 2012 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFRESTClient.h"
#include <time.h>
#include <xlocale.h>
#define AF_ISO8601_MAX_LENGTH 25
// Adopted from SSToolkit NSDate+SSToolkitAdditions
// Created by Sam Soffes
// Copyright (c) 2008-2012 Sam Soffes
// https://github.com/soffes/sstoolkit/
NSDate * AFDateFromISO8601String(NSString *ISO8601String) {
if (!ISO8601String) {
return nil;
}
const char *str = [ISO8601String cStringUsingEncoding:NSUTF8StringEncoding];
char newStr[AF_ISO8601_MAX_LENGTH];
bzero(newStr, AF_ISO8601_MAX_LENGTH);
size_t len = strlen(str);
if (len == 0) {
return nil;
}
// UTC dates ending with Z
if (len == 20 && str[len - 1] == 'Z') {
memcpy(newStr, str, len - 1);
strncpy(newStr + len - 1, "+0000\0", 6);
}
// Timezone includes a semicolon (not supported by strptime)
else if (len == 25 && str[22] == ':') {
memcpy(newStr, str, 22);
memcpy(newStr + 22, str + 23, 2);
}
// Fallback: date was already well-formatted OR any other case (bad-formatted)
else {
memcpy(newStr, str, len > AF_ISO8601_MAX_LENGTH - 1 ? AF_ISO8601_MAX_LENGTH - 1 : len);
}
// Add null terminator
newStr[sizeof(newStr) - 1] = 0;
struct tm tm = {
.tm_sec = 0,
.tm_min = 0,
.tm_hour = 0,
.tm_mday = 0,
.tm_mon = 0,
.tm_year = 0,
.tm_wday = 0,
.tm_yday = 0,
.tm_isdst = -1,
};
strptime_l(newStr, "%FT%T%z", &tm, NULL);
return [NSDate dateWithTimeIntervalSince1970:mktime(&tm)];
}
static NSString * AFPluralizedString(NSString *string) {
if ([string hasSuffix:@"ss"] || [string hasSuffix:@"sh"] || [string hasSuffix:@"ch"]) {
return [[string stringByAppendingString:@"es"] lowercaseString];
} else {
return [[string stringByAppendingString:@"s"] lowercaseString];
}
}
static NSString * AFQueryByAppendingParameters(NSString *query, NSDictionary *parameters) {
static NSCharacterSet *_componentSeparatorCharacterSet = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_componentSeparatorCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"&"];
});
if (!parameters || [parameters count] == 0) {
return query;
}
query = query ? [[query stringByTrimmingCharactersInSet:_componentSeparatorCharacterSet] stringByAppendingString:@"&"] : @"";
NSMutableArray *mutablePairs = [NSMutableArray arrayWithCapacity:[parameters count]];
[parameters enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL *stop) {
[mutablePairs addObject:[NSString stringWithFormat:@"%@=%@", field, value]];
}];
return [query stringByAppendingString:[mutablePairs componentsJoinedByString:@"&"]];
}
@implementation AFRESTClient
- (NSString *)pathForEntity:(NSEntityDescription *)entity {
return AFPluralizedString(entity.name);
}
- (NSString *)pathForObject:(NSManagedObject *)object {
NSString *resourceIdentifier = AFResourceIdentifierFromReferenceObject([(NSIncrementalStore *)object.objectID.persistentStore referenceObjectForObjectID:object.objectID]);
return [[self pathForEntity:object.entity] stringByAppendingPathComponent:[resourceIdentifier lastPathComponent]];
}
- (NSString *)pathForRelationship:(NSRelationshipDescription *)relationship
forObject:(NSManagedObject *)object
{
return [[self pathForObject:object] stringByAppendingPathComponent:relationship.name];
}
#pragma mark - AFIncrementalStoreHTTPClient
#pragma mark Read Methods
- (id)representationOrArrayOfRepresentationsFromResponseObject:(id)responseObject {
if ([responseObject isKindOfClass:[NSArray class]]) {
return responseObject;
} else if ([responseObject isKindOfClass:[NSDictionary class]]) {
// Distinguish between keyed array or individual representation
if ([[responseObject allKeys] count] == 1) {
id value = [responseObject valueForKey:[[responseObject allKeys] lastObject]];
if ([value isKindOfClass:[NSArray class]]) {
return value;
}
}
return responseObject;
}
return responseObject;
}
- (NSDictionary *)representationsForRelationshipsFromRepresentation:(NSDictionary *)representation
ofEntity:(NSEntityDescription *)entity
fromResponse:(NSHTTPURLResponse *)response
{
NSMutableDictionary *mutableRelationshipRepresentations = [NSMutableDictionary dictionaryWithCapacity:[entity.relationshipsByName count]];
[entity.relationshipsByName enumerateKeysAndObjectsUsingBlock:^(id name, id relationship, BOOL *stop) {
id value = [representation valueForKey:name];
if (value) {
if ([relationship isToMany]) {
NSArray *arrayOfRelationshipRepresentations = nil;
if ([value isKindOfClass:[NSArray class]]) {
arrayOfRelationshipRepresentations = value;
} else {
arrayOfRelationshipRepresentations = [NSArray arrayWithObject:value];
}
[mutableRelationshipRepresentations setValue:arrayOfRelationshipRepresentations forKey:name];
} else {
[mutableRelationshipRepresentations setValue:value forKey:name];
}
}
}];
return mutableRelationshipRepresentations;
}
- (NSString *)resourceIdentifierForRepresentation:(NSDictionary *)representation
ofEntity:(NSEntityDescription *)entity
fromResponse:(NSHTTPURLResponse *)response
{
static NSArray *_candidateKeys = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_candidateKeys = [[NSArray alloc] initWithObjects:@"id", @"identifier", @"url", @"URL", nil];
});
NSString *key = [[representation allKeys] firstObjectCommonWithArray:_candidateKeys];
if (key) {
id value = [representation valueForKey:key];
if (value) {
return [value description];
}
}
return nil;
}
- (NSDictionary *)attributesForRepresentation:(NSDictionary *)representation
ofEntity:(NSEntityDescription *)entity
fromResponse:(NSHTTPURLResponse *)response
{
if ([representation isEqual:[NSNull null]]) {
return nil;
}
NSMutableDictionary *mutableAttributes = [representation mutableCopy];
@autoreleasepool {
NSMutableSet *mutableKeys = [NSMutableSet setWithArray:[representation allKeys]];
[mutableKeys minusSet:[NSSet setWithArray:[[entity propertiesByName] allKeys]]];
[mutableAttributes removeObjectsForKeys:[mutableKeys allObjects]];
}
NSSet *keysWithNestedValues = [mutableAttributes keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
return [obj isKindOfClass:[NSArray class]] || [obj isKindOfClass:[NSDictionary class]];
}];
[mutableAttributes removeObjectsForKeys:[keysWithNestedValues allObjects]];
[[entity attributesByName] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([(NSAttributeDescription *)obj attributeType] == NSDateAttributeType) {
id value = [mutableAttributes valueForKey:key];
if (value && ![value isEqual:[NSNull null]]) {
[mutableAttributes setValue:AFDateFromISO8601String(value) forKey:key];
}
}
}];
return mutableAttributes;
}
- (NSMutableURLRequest *)requestForFetchRequest:(NSFetchRequest *)fetchRequest
withContext:(NSManagedObjectContext *)context
{
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
if (self.paginator) {
[mutableParameters addEntriesFromDictionary:[self.paginator parametersForFetchRequest:fetchRequest]];
}
NSMutableURLRequest *mutableRequest = [self requestWithMethod:@"GET" path:[self pathForEntity:fetchRequest.entity] parameters:[mutableParameters count] == 0 ? nil : mutableParameters];
mutableRequest.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
return mutableRequest;
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
pathForObjectWithID:(NSManagedObjectID *)objectID
withContext:(NSManagedObjectContext *)context
{
NSManagedObject *object = [context objectWithID:objectID];
return [self requestWithMethod:method path:[self pathForObject:object] parameters:nil];
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
pathForRelationship:(NSRelationshipDescription *)relationship
forObjectWithID:(NSManagedObjectID *)objectID
withContext:(NSManagedObjectContext *)context
{
NSManagedObject *object = [context objectWithID:objectID];
return [self requestWithMethod:method path:[self pathForRelationship:relationship forObject:object] parameters:nil];
}
- (BOOL)shouldFetchRemoteValuesForRelationship:(NSRelationshipDescription *)relationship
forObjectWithID:(NSManagedObjectID *)objectID
inManagedObjectContext:(NSManagedObjectContext *)context
{
return [relationship isToMany] || ![relationship inverseRelationship];
}
#pragma mark Write Methods
- (NSDictionary *)representationOfAttributes:(NSDictionary *)attributes
ofManagedObject:(NSManagedObject *)managedObject
{
return attributes;
}
- (NSMutableURLRequest *)requestForInsertedObject:(NSManagedObject *)insertedObject {
return [self requestWithMethod:@"POST" path:[self pathForEntity:insertedObject.entity] parameters:[self representationOfAttributes:[insertedObject dictionaryWithValuesForKeys:[insertedObject.entity.attributesByName allKeys]] ofManagedObject:insertedObject]];
}
- (NSMutableURLRequest *)requestForUpdatedObject:(NSManagedObject *)updatedObject {
NSMutableSet *mutableChangedAttributeKeys = [NSMutableSet setWithArray:[[updatedObject changedValues] allKeys]];
[mutableChangedAttributeKeys intersectSet:[NSSet setWithArray:[updatedObject.entity.attributesByName allKeys]]];
return [self requestWithMethod:@"PUT" path:[self pathForObject:updatedObject] parameters:[self representationOfAttributes:[[updatedObject changedValues] dictionaryWithValuesForKeys:[mutableChangedAttributeKeys allObjects]] ofManagedObject:updatedObject]];
}
- (NSMutableURLRequest *)requestForDeletedObject:(NSManagedObject *)deletedObject {
return [self requestWithMethod:@"DELETE" path:[self pathForObject:deletedObject] parameters:nil];
}
#pragma mark - AFHTTPClient
- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations
progressBlock:(void (^)(NSUInteger, NSUInteger))progressBlock
completionBlock:(void (^)(NSArray *))completionBlock
{
for (AFHTTPRequestOperation *operation in operations) {
if ([operation isKindOfClass:[AFHTTPRequestOperation class]]) {
if (!operation.successCallbackQueue) {
operation.successCallbackQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
}
if (!operation.failureCallbackQueue) {
operation.failureCallbackQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
}
}
}
[super enqueueBatchOfHTTPRequestOperations:operations progressBlock:progressBlock completionBlock:completionBlock];
}
@end
#pragma mark -
@interface AFLimitAndOffsetPaginator ()
@property (readwrite, nonatomic, copy) NSString *limitParameter;
@property (readwrite, nonatomic, copy) NSString *offsetParameter;
@end
@implementation AFLimitAndOffsetPaginator
+ (instancetype)paginatorWithLimitParameter:(NSString *)limitParameterName
offsetParameter:(NSString *)offsetParameterName
{
NSParameterAssert(offsetParameterName);
NSParameterAssert(limitParameterName);
AFLimitAndOffsetPaginator *paginator = [[AFLimitAndOffsetPaginator alloc] init];
paginator.limitParameter = limitParameterName;
paginator.offsetParameter = offsetParameterName;
return paginator;
}
- (NSDictionary *)parametersForFetchRequest:(NSFetchRequest *)fetchRequest {
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
if (fetchRequest.fetchOffset > 0) {
[mutableParameters setValue:[NSString stringWithFormat:@"%u", fetchRequest.fetchOffset] forKey:self.offsetParameter];
}
if (fetchRequest.fetchLimit > 0) {
[mutableParameters setValue:[NSString stringWithFormat:@"%u", fetchRequest.fetchLimit] forKey:self.limitParameter];
}
return mutableParameters;
}
@end
#pragma mark -
static NSUInteger const kAFPaginationDefaultPage = 1;
static NSUInteger const kAFPaginationDefaultPerPage = 20;
@interface AFPageAndPerPagePaginator ()
@property (readwrite, nonatomic, copy) NSString *pageParameter;
@property (readwrite, nonatomic, copy) NSString *perPageParameter;
@end
@implementation AFPageAndPerPagePaginator
+ (instancetype)paginatorWithPageParameter:(NSString *)pageParameterName
perPageParameter:(NSString *)perPageParameterName
{
NSParameterAssert(pageParameterName);
NSParameterAssert(perPageParameterName);
AFPageAndPerPagePaginator *paginator = [[AFPageAndPerPagePaginator alloc] init];
paginator.pageParameter = pageParameterName;
paginator.perPageParameter = perPageParameterName;
return paginator;
}
- (NSDictionary *)parametersForFetchRequest:(NSFetchRequest *)fetchRequest {
NSUInteger perPage = fetchRequest.fetchLimit == 0 ? kAFPaginationDefaultPerPage : fetchRequest.fetchLimit;
NSUInteger page = fetchRequest.fetchOffset == 0 ? kAFPaginationDefaultPage : (NSUInteger)floorf((float)fetchRequest.fetchOffset / (float)perPage) + 1;
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
[mutableParameters setValue:[NSString stringWithFormat:@"%u", page] forKey:self.pageParameter];
[mutableParameters setValue:[NSString stringWithFormat:@"%u", perPage] forKey:self.perPageParameter];
return mutableParameters;
}
@end
#pragma mark -
typedef NSDictionary * (^AFPaginationParametersBlock)(NSFetchRequest *fetchRequest);
@interface AFBlockPaginator ()
@property (readwrite, nonatomic, copy) AFPaginationParametersBlock paginationParameters;
@end
@implementation AFBlockPaginator
+ (instancetype)paginatorWithBlock:(NSDictionary * (^)(NSFetchRequest *fetchRequest))block {
NSParameterAssert(block);
AFBlockPaginator *paginator = [[AFBlockPaginator alloc] init];
paginator.paginationParameters = block;
return paginator;
}
- (NSDictionary *)parametersForFetchRequest:(NSFetchRequest *)fetchRequest {
if (self.paginationParameters) {
return self.paginationParameters(fetchRequest);
}
return nil;
}
@end