Skip to content

Instantly share code, notes, and snippets.

@bryanbarnard
Created November 12, 2012 05:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanbarnard/4057721 to your computer and use it in GitHub Desktop.
Save bryanbarnard/4057721 to your computer and use it in GitHub Desktop.
NSURLConnection Sample
//
// SNViewController.m
// SimpleNetwork
//
// Created by Bryan Barnard on 11/11/12.
// Copyright (c) 2012 Bryan Barnard. All rights reserved.
//
#import "SNViewController.h"
@interface SNViewController ()
@end
@implementation SNViewController
@synthesize responseData;
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"viewdidload");
[self fetchNotes];
}
- (void)fetchNotes {
self.responseData = [NSMutableData data];
NSURL *briteredNotes = [NSURL URLWithString:@"http://britrednotes.azurewebsites.net/api/notes?pageIndex=1&pageSize=10"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:briteredNotes];
/* add custom header */
[request addValue:@"0ca532cc-1918-475e-ae30-a4a3ac25625c" forHTTPHeaderField:@"AuthorId"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int code = [httpResponse statusCode];
NSLog(@"HTTP Response Status Code: %d", code);
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError");
//NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
/* this is the meat */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %d bytes of data", [self.responseData length]);
//​=​ ​[​[​N​S​S​t​r​i​n​g​ ​a​l​l​o​c​]​ ​i​n​i​t​W​i​t​h​D​a​t​a​:​ self.responseData​ e​n​c​o​d​i​n​g​:​N​S​U​T​F​8​S​t​r​i​n​g​E​n​c​o​d​i​n​g​]​;
NSString *t = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"jsonCheck: %@", t);
// convert to JSON
NSError *myError = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableContainers error:&myError];
if (!jsonArray) {
NSLog(@"error parsing json response");
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment