Skip to content

Instantly share code, notes, and snippets.

@ayushgoel
Created April 29, 2018 07:09
Show Gist options
  • Save ayushgoel/852ce7ee5c969521efa0039623fbc635 to your computer and use it in GitHub Desktop.
Save ayushgoel/852ce7ee5c969521efa0039623fbc635 to your computer and use it in GitHub Desktop.
Handling network responses
- (void)makeNetworkCall {
NSURL *URL = nil; // replace with own URL
[[NSURLSession sharedSession] dataTaskWithURL:URL
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error != nil) {
NSLog(@"Got error for request with URL: %@", URL);
[self handleError:error];
return;
}
if (![response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(@"Response class, expected:NSHTTPURLResponse got:%@", [response class]);
[self handleWrongResponseClassForResponse:response];
return;
}
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
if (HTTPResponse.statusCode != 200) { // Add more acceptable status codes
NSLog(@"Got non 200 status for request %@", URL);
[self handleNonOkStatusForResponse:HTTPResponse];
return;
}
if (![response.MIMEType isEqualToString:@"application/json"]) { // Replace with acceptable content type
NSLog(@"Response type is not what was expected %@", response.MIMEType);
[self handleIncorrectMIMEForResponse:response];
return;
}
NSDictionary *responseObject = [self parsedObjectFromData:data];
if (responseObject == nil) {
NSLog(@"Response data could not be parsed from data: %@", data);
return;
}
[self handleResponseObject:responseObject];
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment