-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONAPICall.m
71 lines (62 loc) · 2.62 KB
/
JSONAPICall.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
//
// JSONAPICall.m
// AvocadoTest1
//
// Created by Christophe Biocca on 12-01-26.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "JSONAPICall.h"
NSString* JSON_API_ERROR = @"com.croutonlabs.server.json";
@implementation JSONAPICall
+(NSData*)getJSONData:(id)object{
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization
dataWithJSONObject:object
options:0
error:&error];
NSAssert(!error, @"INVALID JSON, WHAT ARE YOU? A MONKEY?");
//lol @Christophe
return jsonData;
}
+(id)sendPOSTRequestForLocation:(NSString *)location withJSONData:(NSDictionary *)json andDelegate:(id<APICallDelegate>)delegate{
return [self sendPOSTRequestForLocation:location
withBodyData:[self getJSONData:json]
withDelegate:delegate];
}
+(id)sendPOSTRequestForLocation:(NSString *)location withJSONData:(NSDictionary *)json
success:(void (^)(id))success
failure:(void (^)(id, NSError *))failure{
return [self sendPOSTRequestForLocation:location
withBodyData:[self getJSONData:json]
success:success
failure:failure];
}
-(void)postCompletionHook{
[super postCompletionHook];
NSError* parsingError = nil;
CLLog(LOG_LEVEL_INFO, [NSString stringWithFormat:@"Parsing JSON: \n%@", [[NSString alloc] initWithData:[self rawData] encoding:NSASCIIStringEncoding]]);
NSDictionary* parsed = [NSJSONSerialization JSONObjectWithData:[self rawData]
options:0
error:&parsingError];
NSError* originalError = [self error];
if(parsingError){
if(!originalError){
[self setError:parsingError];
}
} else if(originalError && // Bad requests usually have a parsable json explanation attached to them.
[originalError domain] == SERVER_HTTP_ERROR_DOMAIN &&
[originalError code] == 400){
NSDictionary* errorObject = [parsed objectForKey:@"error"];
if(errorObject){
[self replaceError:[NSError errorWithDomain:JSON_API_ERROR code:0 userInfo:errorObject]];
}
} else {
jsonData = parsed;
}
}
-(NSDictionary*)jsonData{
NSAssert([self completed], @"Can't access jsonData before request completes!");
NSAssert(![self error], @"Can't access jsonData when there is an error!");
return jsonData;
}
@end