Skip to content

Instantly share code, notes, and snippets.

@deivuh
Last active August 29, 2015 14:03
Show Gist options
  • Save deivuh/3f58fde64b5125cfede0 to your computer and use it in GitHub Desktop.
Save deivuh/3f58fde64b5125cfede0 to your computer and use it in GitHub Desktop.
Objective C REST request, receive and parse json into dictionary
- (void) sendRequest {
receivedData = [[NSMutableData alloc] init];
NSLog(@"Initial data length: %d",[receivedData length]);
requestURL = [NSString stringWithFormat:@"<#URL HERE#>"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:requestURL]];
[request setHTTPMethod:@"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
NSLog(@"connection Started");
}
#pragma mark -
#pragma mark NSURLConnection Delegates
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Failed with error: %@", error.description);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
int responseCode = ((NSHTTPURLResponse*)response).statusCode;
NSLog(@"Response: %d", responseCode );
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error;
// Print the raw response
NSLog(@"Data string: %@", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);
NSLog(@"Connection did finish loading");
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:receivedData
options:NSUTF8StringEncoding
error:&error];
if (error) {
NSLog(@"Parsing error: %@", error.description);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment