Created
May 12, 2016 17:13
-
-
Save kevinjstewart/1b18be9589ae2ae5ba92721f6365e886 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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