Skip to content

Instantly share code, notes, and snippets.

@aijaz
Created August 22, 2017 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aijaz/f9bbbff8efd850f3a2cdb71b71c111af to your computer and use it in GitHub Desktop.
Save aijaz/f9bbbff8efd850f3a2cdb71b71c111af to your computer and use it in GitHub Desktop.
Simple example of using NSURLSession - Objective-C
#import "CCNetwork.h"
@implementation CCNetwork
+(void) retrieveJSONAtLocation: (NSString *) urlString completionHandler: (void (^)(NSData *data, NSURLResponse *response, NSError *error)) handler {
NSURL *url = [[NSBundle mainBundle] URLForResource:urlString withExtension:@"json"];
[CCNetwork retrieveJSONAtURL:url completionHandler:handler];
}
+(void) retrieveJSONAtURL: (NSURL *) url completionHandler: (void (^)(NSData *data, NSURLResponse *response, NSError *error)) handler {
NSURLSessionConfiguration *conf = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *sessionWithoutADelegate = [NSURLSession sessionWithConfiguration:conf];
NSURLSessionDataTask * task = [sessionWithoutADelegate dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// convert to an object
NSError * jsonError;
NSDictionary * jsonObject = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error: &jsonError];
// save to database
[CCDatabase saveJSONObject:jsonObject];
handler(data, response, error);
[sessionWithoutADelegate finishTasksAndInvalidate];
}];
[task resume];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment