@@ -30,20 +30,14 @@ - (id)initWithBaseURL:(NSURL *)url
30
30
{
31
31
self = [super initWithBaseURL: url];
32
32
if (self) {
33
- [self registerHTTPOperationClass: [AFJSONRequestOperation class ]];
34
- [self setDefaultHeader: @" Accept" value: @" application/json" ];
35
- [self setAllowsInvalidSSLCertificate: YES ];
36
-
37
- typeof (self) __weak __self = self;
38
- [self setReachabilityStatusChangeBlock: ^(AFNetworkReachabilityStatus status) {
39
- [__self apiReachabilityChanged: status];
40
- }];
33
+ [self setRequestSerializer: [AFJSONRequestSerializer serializer ]];
34
+ [self setResponseSerializer: [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingAllowFragments ]];
41
35
42
36
@try {
43
37
if ([[NSFileManager defaultManager ] fileExistsAtPath: PATH_STORE_STATE]) {
44
38
NSDictionary * dict = [NSKeyedUnarchiver unarchiveObjectWithFile: PATH_STORE_STATE];
45
39
_globalObjectStore = [dict objectForKey: @" objectStore" ];
46
- _user = [dict objectForKey: @" user" ];
40
+ [ self setUser: [dict objectForKey: @" user" ] ];
47
41
}
48
42
49
43
if ([[NSFileManager defaultManager ] fileExistsAtPath: PATH_ACTIONS_STATE])
@@ -58,13 +52,12 @@ - (id)initWithBaseURL:(NSURL *)url
58
52
if (!_transactionsQueue)
59
53
_transactionsQueue = [NSMutableArray array ];
60
54
[self performNextAction ];
61
-
62
- [[AFNetworkActivityIndicatorManager sharedManager ] setEnabled: YES ];
63
55
}
64
56
return self;
65
57
}
66
58
67
- - (void )apiReachabilityChanged : (AFNetworkReachabilityStatus)status {
59
+ - (void )apiReachabilityChanged : (AFNetworkReachabilityStatus)status
60
+ {
68
61
if (status == AFNetworkReachabilityStatusNotReachable) {
69
62
if (!_hasDisplayedDisconnectionNotice) {
70
63
_hasDisplayedDisconnectionNotice = YES ;
@@ -104,38 +97,40 @@ - (void)updateDiskCacheDebounced
104
97
105
98
#pragma mark Requesting Object Data
106
99
107
- - (void )getModelAtPath : (NSString *)path userTriggered : (BOOL )triggered success : (void (^)(id responseObject))successCallback failure : (void (^)(NSError *err))failureCallback
100
+ - (void )dictionaryAtPath : (NSString *)path userTriggered : (BOOL )triggered success : (void (^)(id responseObject))successCallback failure : (void (^)(NSError *err))failureCallback
108
101
{
109
102
[self requestPath: path withMethod: @" GET" withParameters: nil userTriggered: triggered expectedClass: [NSDictionary class ] success: successCallback failure: failureCallback];
110
103
}
111
104
112
- - (void )getCollectionAtPath : (NSString *)path userTriggered : (BOOL )triggered success : (void (^)(id responseObject))successCallback failure : (void (^)(NSError *err))failureCallback
105
+ - (void )arrayAtPath : (NSString *)path userTriggered : (BOOL )triggered success : (void (^)(id responseObject))successCallback failure : (void (^)(NSError *err))failureCallback
113
106
{
114
107
[self requestPath: path withMethod: @" GET" withParameters: nil userTriggered: triggered expectedClass: [NSArray class ] success: successCallback failure: failureCallback];
115
108
}
116
109
117
110
- (void )requestPath : (NSString *)path withMethod : (NSString *)method withParameters : params userTriggered : (BOOL )triggered expectedClass : (Class )expectation success : (void (^)(id responseObject))successCallback failure : (void (^)(NSError *err))failureCallback
118
111
{
119
- NSURLRequest *request = [self requestWithMethod: method path: path parameters: params];
120
- AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest: request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
112
+ if (!self.baseURL )
113
+ @throw [NSException exceptionWithName: @" Cannot make request" reason: @" Base URL is not defined." userInfo: nil ];
114
+
115
+ NSMutableURLRequest *request = [self .requestSerializer requestWithMethod: method URLString: [[NSURL URLWithString: path relativeToURL: self .baseURL] absoluteString ] parameters: params error: nil ];
116
+ AFHTTPRequestOperation * operation = [self HTTPRequestOperationWithRequest: request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
121
117
if (expectation && ([responseObject isKindOfClass: expectation] == NO )) {
122
- NSError * err = [NSError errorWithExpectationFailure: [responseObject class ]];
118
+ NSError * error = [NSError errorWithExpectationFailure: [responseObject class ]];
123
119
if (triggered)
124
- [self criticalRequestFailed: err ];
120
+ [self displayNetworkError: error forOperation: operation withGoal: @" Request " ];
125
121
if (failureCallback)
126
- failureCallback (err );
122
+ failureCallback (error );
127
123
return ;
128
124
}
129
125
successCallback (responseObject);
130
-
131
- } failure: ^(AFHTTPRequestOperation *operation, NSError *err ) {
126
+
127
+ } failure: ^(AFHTTPRequestOperation *operation, NSError *error ) {
132
128
if (triggered)
133
- [self criticalRequestFailed: err ];
129
+ [self displayNetworkError: error forOperation: operation withGoal: @" Request " ];
134
130
if (failureCallback)
135
- failureCallback (err );
131
+ failureCallback (error );
136
132
}];
137
-
138
- [self enqueueHTTPRequestOperation: operation];
133
+ [self .operationQueue addOperation: operation];
139
134
}
140
135
141
136
- (MModel*)globalObjectWithID : (NSString *)ID ofClass : (Class )type
@@ -158,8 +153,10 @@ - (void)addGlobalObject:(MModel*)model
158
153
- (void )setUser : (MUser *)user
159
154
{
160
155
_user = user;
161
- if (user == nil )
162
- [self clearAuthorizationHeader ];
156
+ if (user)
157
+ [[self requestSerializer ] setAuthorizationHeaderFieldWithUsername: [user credentialUsername ] password: [user credentialPassword ]];
158
+ else
159
+ [[self requestSerializer ] clearAuthorizationHeader ];
163
160
164
161
[self updateDiskCache: YES ];
165
162
[[NSNotificationCenter defaultCenter ] postNotificationName: NOTIF_USER_CHANGED object: nil ];
@@ -179,7 +176,7 @@ - (void)queueAPITransaction:(MAPITransaction*)a
179
176
return ;
180
177
181
178
[_transactionsQueue addObject: a];
182
- if (([self networkReachabilityStatus ] != AFNetworkReachabilityStatusNotReachable) && (![a started ]))
179
+ if (([[ self reachabilityManager ] networkReachabilityStatus ] != AFNetworkReachabilityStatusNotReachable) && (![a started ]))
183
180
[a performDeferred ];
184
181
185
182
NSLog (@" API: Queued API action: %@ " , [a description ]);
@@ -212,7 +209,7 @@ - (void)finishedAPITransaction:(MAPITransaction*)a withError:(NSError*)err
212
209
} else if (err) {
213
210
// TODO: Additional logic was here... Do we always want to throw away the transaction if it fails once?
214
211
[self dequeueAPITransaction: a];
215
- [self criticalRequestFailed: err];
212
+ [self displayNetworkError: err forOperation: nil withGoal: @" Request " ];
216
213
}
217
214
[[NSNotificationCenter defaultCenter ] postNotificationName: NOTIF_API_QUEUE_CHANGED object: nil ];
218
215
}
@@ -226,7 +223,7 @@ - (void)dequeueAPITransaction:(MAPITransaction*)a
226
223
227
224
- (void )performNextActionIfReconnected
228
225
{
229
- if ([self networkReachabilityStatus ] != AFNetworkReachabilityStatusNotReachable)
226
+ if ([[ self reachabilityManager ] networkReachabilityStatus ] != AFNetworkReachabilityStatusNotReachable)
230
227
[self performNextAction ];
231
228
else {
232
229
NSString * msg = @" Please connect to the internet and try to sync again." ;
@@ -248,24 +245,23 @@ - (void)performNextAction
248
245
249
246
#pragma mark Handling Request Results
250
247
251
- - (void )criticalRequestFailed : (NSError *)err
248
+ - (void )displayNetworkError : (NSError *)error forOperation : (AFHTTPRequestOperation*) operation withGoal : ( NSString *) goal
252
249
{
253
- NSData * jsonData = [[err.userInfo objectForKey: @" NSLocalizedRecoverySuggestion" ] dataUsingEncoding: NSUTF8StringEncoding];
254
- NSString * message = err.localizedDescription ;
255
-
256
- if (jsonData) {
257
- NSDictionary * json = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingAllowFragments error: NULL ];
258
- if (json) message = [json objectForKey: @" error" ];
259
- }
250
+ NSString * message = nil ;
260
251
261
- if ([err code ] == 401 )
252
+ if ([[operation responseObject ] objectForKey: @" error" ])
253
+ message = [[operation responseObject ] objectForKey: @" error" ];
254
+
255
+ else if (([error code ] == 401 ) || ([[operation response ] statusCode ] == 401 ))
262
256
message = @" Please check your email address and password." ;
263
257
264
- if (message && [message isKindOfClass: [ NSString class ]])
265
- [[[UIAlertView alloc ] initWithTitle: @" Error " message: message delegate: nil cancelButtonTitle: @" OK " otherButtonTitles: nil ] show ];
258
+ else
259
+ message = [error localizedDescription ];
266
260
267
- [[NSNotificationCenter defaultCenter ] postNotificationName: NOTIF_API_QUEUE_CHANGED object: nil ];
261
+ NSString * title = [goal stringByAppendingString: @" Failed" ];
262
+ [[[UIAlertView alloc ] initWithTitle: title message: message delegate: nil cancelButtonTitle: @" OK" otherButtonTitles: nil ] show ];
268
263
}
269
264
270
265
266
+
271
267
@end
0 commit comments