@@ -225,12 +225,24 @@ - (void)sendRequest:(NSURLRequest *)request onSuccess:(void (^)(NSDictionary *))
225225 {
226226 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
227227 NSInteger responseCode = httpResponse.statusCode ;
228+
229+ // Handle network errors
230+ if (error != nil ) {
231+ NSString *reason = [NSString stringWithFormat: @" %@ " , error];
232+ if (onFailure != nil ) onFailure (reason, nil );
233+ return ;
234+ }
228235
229236 NSError *jsonError = nil ;
230- id json = [NSJSONSerialization
231- JSONObjectWithData: data
232- options: 0
233- error: &jsonError];
237+ id json = nil ;
238+
239+ // Only try to parse JSON if data exists, otherwise JSONObjectWithData throws an exception
240+ if ([data length ] > 0 ) {
241+ json = [NSJSONSerialization
242+ JSONObjectWithData: data
243+ options: 0
244+ error: &jsonError];
245+ }
234246
235247 if (responseCode == 401 ) {
236248 if (onFailure != nil ) onFailure (@" Invalid API Key" , data);
@@ -249,7 +261,7 @@ - (void)sendRequest:(NSURLRequest *)request onSuccess:(void (^)(NSDictionary *))
249261 onFailure (errorMessage, data);
250262 }
251263 } else if (responseCode == 200 ) {
252- if ([data length ] > 0 && error == nil ) {
264+ if ([data length ] > 0 ) {
253265 if (jsonError) {
254266 NSString *reason = [NSString stringWithFormat: @" Could not parse json: %@ " , [[NSString alloc ] initWithData: data encoding: NSUTF8StringEncoding]];
255267 if (onFailure != nil ) onFailure (reason, data);
@@ -260,11 +272,8 @@ - (void)sendRequest:(NSURLRequest *)request onSuccess:(void (^)(NSDictionary *))
260272 } else {
261273 if (onFailure != nil ) onFailure (@" Response is not a dictionary" , data);
262274 }
263- } else if ([data length ] == 0 && error == nil ) {
275+ } else {
264276 if (onFailure != nil ) onFailure (@" No data received" , data);
265- } else if (error != nil ) {
266- NSString *reason = [NSString stringWithFormat: @" %@ " , error];
267- if (onFailure != nil ) onFailure (reason, nil );
268277 }
269278 } else {
270279 if (onFailure != nil ) onFailure ([NSString stringWithFormat: @" Received non-200 response: %ld " , (long ) responseCode], data);
0 commit comments