Skip to content

Instantly share code, notes, and snippets.

@kevinjstewart
Created May 12, 2016 17:13
Show Gist options
  • Save kevinjstewart/1b18be9589ae2ae5ba92721f6365e886 to your computer and use it in GitHub Desktop.
Save kevinjstewart/1b18be9589ae2ae5ba92721f6365e886 to your computer and use it in GitHub Desktop.
//Class declaration
@interface ClassName () <NSURLSessionDelegate> // Implement Delegate
//Init Method to configure session for datatask
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
// Create Session with the default configuration
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:nil];
}
return self;
}
// Grab the JSON data and assign it to the beers array
- (void)fetchJSONData
{
// Create request
NSString *requestString = @"https://prost.herokuapp.com/api/v1/beer/rand"; // This is your API location
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// make a data task with completion handler that assigns the result to the beers property
NSURLSessionTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error)
{
if (data == nil)
{
return;
}
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
// the jsonObject is not an NSDictionary with the stored JSON data
}];
// DataTasks are created in a paused state and must be resumed to start
[dataTask resume];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment