-
Notifications
You must be signed in to change notification settings - Fork 0
/
FBRequest.m
363 lines (290 loc) · 11.1 KB
/
FBRequest.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
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBRequest.h"
#import "JSON.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
// global
static NSString* kUserAgent = @"FacebookConnect";
static NSString* kStringBoundary = @"3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
static const int kGeneralErrorCode = 10000;
static const NSTimeInterval kTimeoutInterval = 180.0;
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation FBRequest
@synthesize delegate = _delegate,
url = _url,
httpMethod = _httpMethod,
params = _params,
connection = _connection,
responseText = _responseText;
//////////////////////////////////////////////////////////////////////////////////////////////////
// class public
+ (FBRequest *)getRequestWithParams:(NSMutableDictionary *) params
httpMethod:(NSString *) httpMethod
delegate:(id<FBRequestDelegate>) delegate
requestURL:(NSString *) url {
FBRequest* request = [[[FBRequest alloc] init] autorelease];
request.delegate = delegate;
request.url = url;
request.httpMethod = httpMethod;
request.params = params;
request.connection = nil;
request.responseText = nil;
return request;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// private
+ (NSString *)serializeURL:(NSString *)baseUrl
params:(NSDictionary *)params {
return [self serializeURL:baseUrl params:params httpMethod:@"GET"];
}
/**
* Generate get URL
*/
+ (NSString*)serializeURL:(NSString *)baseUrl
params:(NSDictionary *)params
httpMethod:(NSString *)httpMethod {
NSURL* parsedURL = [NSURL URLWithString:baseUrl];
NSString* queryPrefix = parsedURL.query ? @"&" : @"?";
NSMutableArray* pairs = [NSMutableArray array];
for (NSString* key in [params keyEnumerator]) {
if (([[params valueForKey:key] isKindOfClass:[UIImage class]])
||([[params valueForKey:key] isKindOfClass:[NSData class]])) {
if ([httpMethod isEqualToString:@"GET"]) {
NSLog(@"can not use GET to upload a file");
}
continue;
}
NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL, /* allocator */
(CFStringRef)[params objectForKey:key],
NULL, /* charactersToLeaveUnescaped */
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
[pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
[escaped_value release];
}
NSString* query = [pairs componentsJoinedByString:@"&"];
return [NSString stringWithFormat:@"%@%@%@", baseUrl, queryPrefix, query];
}
/**
* Body append for POST method
*/
- (void)utfAppendBody:(NSMutableData *)body data:(NSString *)data {
[body appendData:[data dataUsingEncoding:NSUTF8StringEncoding]];
}
/**
* Generate body for POST method
*/
- (NSMutableData *)generatePostBody {
NSMutableData *body = [NSMutableData data];
NSString *endLine = [NSString stringWithFormat:@"\r\n--%@\r\n", kStringBoundary];
NSMutableDictionary *dataDictionary = [NSMutableDictionary dictionary];
[self utfAppendBody:body data:[NSString stringWithFormat:@"--%@\r\n", kStringBoundary]];
for (id key in [_params keyEnumerator]) {
if (([[_params valueForKey:key] isKindOfClass:[UIImage class]])
||([[_params valueForKey:key] isKindOfClass:[NSData class]])) {
[dataDictionary setObject:[_params valueForKey:key] forKey:key];
continue;
}
[self utfAppendBody:body
data:[NSString
stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",
key]];
[self utfAppendBody:body data:[_params valueForKey:key]];
[self utfAppendBody:body data:endLine];
}
if ([dataDictionary count] > 0) {
for (id key in dataDictionary) {
NSObject *dataParam = [dataDictionary valueForKey:key];
if ([dataParam isKindOfClass:[UIImage class]]) {
NSData* imageData = UIImagePNGRepresentation((UIImage*)dataParam);
[self utfAppendBody:body
data:[NSString stringWithFormat:
@"Content-Disposition: form-data; filename=\"%@\"\r\n", key]];
[self utfAppendBody:body
data:[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"]];
[body appendData:imageData];
} else {
NSAssert([dataParam isKindOfClass:[NSData class]],
@"dataParam must be a UIImage or NSData");
[self utfAppendBody:body
data:[NSString stringWithFormat:
@"Content-Disposition: form-data; filename=\"%@\"\r\n", key]];
[self utfAppendBody:body
data:[NSString stringWithString:@"Content-Type: content/unknown\r\n\r\n"]];
[body appendData:(NSData*)dataParam];
}
[self utfAppendBody:body data:endLine];
}
}
return body;
}
/**
* Formulate the NSError
*/
- (id)formError:(NSInteger)code userInfo:(NSDictionary *) errorData {
return [NSError errorWithDomain:@"facebookErrDomain" code:code userInfo:errorData];
}
/**
* parse the response data
*/
- (id)parseJsonResponse:(NSData *)data error:(NSError **)error {
NSString* responseString = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]
autorelease];
SBJSON *jsonParser = [[SBJSON new] autorelease];
if ([responseString isEqualToString:@"true"]) {
return [NSDictionary dictionaryWithObject:@"true" forKey:@"result"];
} else if ([responseString isEqualToString:@"false"]) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode
userInfo:[NSDictionary
dictionaryWithObject:@"This operation can not be completed"
forKey:@"error_msg"]];
}
return nil;
}
id result = [jsonParser objectWithString:responseString];
if (![result isKindOfClass:[NSArray class]]) {
if ([result objectForKey:@"error"] != nil) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode
userInfo:result];
}
return nil;
}
if ([result objectForKey:@"error_code"] != nil) {
if (error != nil) {
*error = [self formError:[[result objectForKey:@"error_code"] intValue] userInfo:result];
}
return nil;
}
if ([result objectForKey:@"error_msg"] != nil) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode userInfo:result];
}
}
if ([result objectForKey:@"error_reason"] != nil) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode userInfo:result];
}
}
}
return result;
}
/*
* private helper function: call the delegate function when the request
* fails with error
*/
- (void)failWithError:(NSError *)error {
if ([_delegate respondsToSelector:@selector(request:didFailWithError:)]) {
[_delegate request:self didFailWithError:error];
}
}
/*
* private helper function: handle the response data
*/
- (void)handleResponseData:(NSData *)data {
if ([_delegate respondsToSelector:
@selector(request:didLoadRawResponse:)]) {
[_delegate request:self didLoadRawResponse:data];
}
if ([_delegate respondsToSelector:@selector(request:didLoad:)] ||
[_delegate respondsToSelector:
@selector(request:didFailWithError:)]) {
NSError* error = nil;
id result = [self parseJsonResponse:data error:&error];
if (error) {
[self failWithError:error];
} else if ([_delegate respondsToSelector:
@selector(request:didLoad:)]) {
[_delegate request:self didLoad:(result == nil ? data : result)];
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// public
/**
* @return boolean - whether this request is processing
*/
- (BOOL)loading {
return !!_connection;
}
/**
* make the Facebook request
*/
- (void)connect {
if ([_delegate respondsToSelector:@selector(requestLoading:)]) {
[_delegate requestLoading:self];
}
NSString* url = [[self class] serializeURL:_url params:_params httpMethod:_httpMethod];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:kTimeoutInterval];
[request setValue:kUserAgent forHTTPHeaderField:@"User-Agent"];
[request setHTTPMethod:self.httpMethod];
if ([self.httpMethod isEqualToString: @"POST"]) {
NSString* contentType = [NSString
stringWithFormat:@"multipart/form-data; boundary=%@", kStringBoundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[self generatePostBody]];
}
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
/**
* Free internal structure
*/
- (void)dealloc {
[_connection cancel];
[_connection release];
[_responseText release];
[_url release];
[_httpMethod release];
[_params release];
[super dealloc];
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseText = [[NSMutableData alloc] init];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([_delegate respondsToSelector:
@selector(request:didReceiveResponse:)]) {
[_delegate request:self didReceiveResponse:httpResponse];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseText appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self handleResponseData:_responseText];
[_responseText release];
_responseText = nil;
[_connection release];
_connection = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self failWithError:error];
[_responseText release];
_responseText = nil;
[_connection release];
_connection = nil;
}
@end