ServerAPI.m
14 KB
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
//
// ServerAPI.m
// LifeLog
//
// Created by Nguyen Van Phong on 7/30/17.
// Copyright © 2017 PhongNV. All rights reserved.
//
#import "ServerAPI.h"
NSString *const kServerAddress = @"http://clover.timesfun.jp:9001/";
NSString *const kUser = @"KEY_USER";
NSString *const kToken = @"KEY_TOKEN";
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self UTF8String];
int sourceLen = (int)strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
@end
@implementation ServerAPI
static ServerAPI *_server = nil;
@synthesize timeOutInterval = _timeOutInterval;
+ (instancetype)server
{
@synchronized(self) {
if (_server == nil) {
_server = [[ServerAPI alloc] init];
}
}
return _server;
}
- (instancetype)init
{
self = [super init];
if (self != nil) {
self.timeOutInterval = 150;
}
return self;
}
// Login
- (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion
{
[self _request:[kServerAddress stringByAppendingFormat: @"login"] method:@"POST" paras:@{@"email":email, @"password": password} completion:^(NSData *data, NSError *error) {
if (completion == NULL) {
return ;
}
if (error == nil)
{
NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
int status = [dataResult[@"status"] intValue];
if (status == 1) { // status = 1 success
NSString *token = dataResult[@"result"][@"token"];
NSDictionary *dictUser = dataResult[@"result"][@"user"];
User *user = [[User alloc] init];
user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]];
user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]];
user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]];
user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]];
user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]];
user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]];
user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]];
user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]];
user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue];
user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue];
user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue];
user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]];
user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]];
user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]];
user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]];
user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]];
user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue];
user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue];
user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue];
user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue];
user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue];
user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue];
user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue];
completion(user, token, nil);
}
else { // status = 0 error
NSString *message = dataResult[@"message"];
NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
completion(nil, nil, loginFaild);
}
}
else
{
completion(nil, nil, error);
}
}];
}
// Register
- (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion {
[self _request:[kServerAddress stringByAppendingFormat: @"register"] method:@"POST" paras:params completion:^(NSData *data, NSError *error) {
if (completion == NULL) {
return ;
}
if (error == nil)
{
NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
int status = [dataResult[@"status"] intValue];
if (status == 1) { // status = 1 success
NSString *token = dataResult[@"result"][@"token"];
NSDictionary *dictUser = dataResult[@"result"][@"user"];
User *user = [[User alloc] init];
user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]];
user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]];
user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]];
user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]];
user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]];
user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]];
user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]];
user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]];
user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue];
user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue];
user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue];
user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]];
user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]];
user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]];
user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]];
user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]];
user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue];
user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue];
user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue];
user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue];
user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue];
user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue];
user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue];
completion(user, token, nil);
}
else { // status = 0 error
NSString *message = dataResult[@"message"];
NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
completion(nil, nil, loginFaild);
}
}
else
{
completion(nil, nil, error);
}
}];
}
- (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion {
[self _request:[kServerAddress stringByAppendingFormat: @"forgetPass"] method:@"POST" paras:@{@"email":email} completion:^(NSData *data, NSError *error) {
if (completion == NULL) {
return ;
}
if (error == nil)
{
NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
int status = [dataResult[@"status"] intValue];
if (status == 1) { // status = 1 success
completion(nil);
}
else { // status = 0 error
NSString *message = dataResult[@"message"];
NSError *forgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
completion(forgetPass);
}
}
else
{
completion(error);
}
}];
}
- (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion {
[self _request:[kServerAddress stringByAppendingFormat: @"forgetPass/confirm"] method:@"POST" paras:@{@"email":email, @"code_confirm": confirm} completion:^(NSData *data, NSError *error) {
if (completion == NULL) {
return ;
}
if (error == nil)
{
NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
int status = [dataResult[@"status"] intValue];
if (status == 1) { // status = 1 success
completion(nil);
}
else { // status = 0 error
NSString *message = dataResult[@"message"];
NSError *confirmForgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
completion(confirmForgetPass);
}
}
else
{
completion(error);
}
}];
}
- (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion {
NSDictionary *dict = nil;
NSString *base64Encoded = [data base64EncodedStringWithOptions:0];
if (token != nil) {
dict = @{@"token":token, @"img": base64Encoded};
}
else {
dict = @{@"img": base64Encoded};
}
[self _request:[kServerAddress stringByAppendingFormat: @"upload-image"] method:@"POST" paras:dict completion:^(NSData *data, NSError *error) {
if (completion == NULL) {
return ;
}
if (error == nil)
{
NSDictionary *dataResult = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
NSString *image_profile = [NSString stringWithFormat:@"%@", dataResult[@"message"]];
completion(image_profile, nil);
}
else
{
completion(nil, error);
}
}];
}
#pragma mark - Private Function
- (NSData *) _encodeDictionary: (NSDictionary *) dictionary
{
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (id key in dictionary)
{
NSString *encodedValue = [[dictionary[key] description] urlencode];
NSString *encodedKey = [[key description] urlencode];//[[key description] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:@"&"];
return [encodedDictionary dataUsingEncoding: NSUTF8StringEncoding];
}
- (void) _request:(NSString *)address method:(NSString *)method paras:(NSDictionary *)paras completion:(void (^)(NSData *data, NSError *error))completion
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:address]];
request.HTTPMethod = method;
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
[request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
[request setTimeoutInterval:self.timeOutInterval];
if (paras != nil)
{
NSData *encodedData = [self _encodeDictionary: paras];
[request setValue: [NSString stringWithFormat: @"%lu", (unsigned long) encodedData.length] forHTTPHeaderField: @"Content-Length"];
[request setValue: @"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField: @"Content-Type"];
[request setHTTPBody: encodedData];
}
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (completion == NULL) {
return ;
}
if (error == nil)
{
completion(data, nil);
}
else
{
completion(nil, error);
}
}];
[task resume];
}
@end