-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseApiRequest.m
100 lines (84 loc) · 2.58 KB
/
BaseApiRequest.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
//
// BaseApiRequest.m
// VKMusic
//
// Created by Evgeniy Kirpichenko on 2/17/13.
// Copyright (c) 2013 Evgeniy Kirpichenko. All rights reserved.
//
#import "BaseApiRequest.h"
#import "ObjectMapping.h"
@implementation BaseApiRequest
#pragma mark -
#pragma mark life cycle
- (id)init
{
if (self = [super init]) {
[self setBaseURL:kApiBaseURL];
[self setAccessToken:[[[SettingsManager sharedInstance] signedUser] accessToken]];
}
return self;
}
- (void)dealloc
{
[self setBaseURL:nil];
[self setApiPath:nil];
[self setAccessToken:nil];
}
#pragma mark -
#pragma mark public methods
- (NSURLRequest *)apiURLRequest
{
NSMutableString *urlString = [NSMutableString stringWithFormat:@"%@%@?access_token=%@",
[self baseURL],
[self apiPath],
[self accessToken]];
NSString *query = [self apiQuery];
if (query != nil) {
[urlString appendFormat:@"&%@",query];
}
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return [NSURLRequest requestWithURL:[NSURL URLWithString:encodedString]];
}
- (NSString *)apiQuery
{
[NSException raise:@"Exception:" format:@"Implement - (NSString *)apiQuery method in subclass"];
return nil;
}
- (ObjectMapping *)responseObjectsMapping
{
[NSException raise:@"Exception" format:@"Implement - (ObjectMapping *)responseObjectsMapping method in subclass"];
return nil;
}
- (id)parseJSONResponse:(id)JSON
{
id responseData = [JSON objectForKey:@"response"];
if (responseData == nil) {
return nil;
}
ObjectMapping *objectMapping = [self responseObjectsMapping];
if ([responseData isKindOfClass:[NSArray class]]) {
return [self parseArray:responseData withObjectMapping:objectMapping];
}
else {
return [objectMapping mappedObjectWithProperties:responseData];
}
}
- (id)parseArray:(id)JSON withObjectMapping:(ObjectMapping *)objectMapping
{
NSMutableArray *parsedList = [NSMutableArray arrayWithCapacity:[JSON count]];
for (NSDictionary *objectProperties in JSON) {
id object = [self parseObject:objectProperties withObjectMapping:objectMapping];
if (object != nil) {
[parsedList addObject:object];
}
}
return parsedList;
}
- (id)parseObject:(id)JSON withObjectMapping:(ObjectMapping *)objectMapping
{
if ([JSON isKindOfClass:[NSDictionary class]]) {
return [objectMapping mappedObjectWithProperties:JSON];
}
return nil;
}
@end