Created
August 22, 2017 16:13
-
-
Save aijaz/f9bbbff8efd850f3a2cdb71b71c111af to your computer and use it in GitHub Desktop.
Simple example of using NSURLSession - Objective-C
This file contains 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
#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