Skip to content

Instantly share code, notes, and snippets.

@Shosta
Created November 23, 2017 23:39
Show Gist options
  • Save Shosta/a011dde7ae6b8f735c0c1110a9cce7d0 to your computer and use it in GitHub Desktop.
Save Shosta/a011dde7ae6b8f735c0c1110a9cce7d0 to your computer and use it in GitHub Desktop.
Download Asynchronously using block objects - Objective-C
@implementation ViewController
- (void)loadDataAsync{
// Download the Objects from a JSON file on the server
Downloader *dl = [[Downloader alloc] init];
[dl downloadObjects:self.aID andCompletionHandler:^(NSArray *objectsArray){
// Set the data to your model for instance
// self.mArray = objectsArray;
// Perform refresh on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
// Refresh a tableView for instance
// [self.tableView reloadData];
});
}];
}
@end
@implementation Downloader
/**
Implement this function to return the default values for the download.
*/
- (NSArray *)defaultObjects{
return nil;
}
/**
Download Asynchronously using block objects from a JSON file.
*/
- (void)downloadObjects:(void(^)(NSArray *aArray))completionHandler{
NSURL *aURL = [NSURL URLWithString:@"http://the/url/file.json"];
// This NSMUtableArray is the one that we are going to pass to the completion handler in order to do some work asynchronously.
__block NSMutableArray *objectsArray = [[NSMutableArray alloc] init];
NSURLSessionDownloadTask *downloadQuizzIDsTask = [[NSURLSession sharedSession]
downloadTaskWithURL:aURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 2
if(!downloadError){
NSData *jsonData = [NSData dataWithContentsOfURL:location];
NSError *jsonError = nil;
NSDictionary *jsonAsADict = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&jsonError];
if(! jsonError) {
for (NSDictionary *aDict in [jsonAsADict objectForKey:@"theKey"]){
// Do the work on the object here
}
} else {
// Handle the parsing error if necessary
NSLog(@"Error in parsing JSON");
}
completionHandler(objectsArray);
}else{
// Handle the download error
/* Download a default set of objects and send them for completion.
NSArray *defaultObjects = [self defaultObjects];
completionHandler(defaultObjects);*/
}
}];
// 1
[downloadQuizzIDsTask resume];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment