My application has the following method that uses NSURLSession
to output movie data from a web service in JSON format:
- (void) downloadMovieData {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSURL *url = [NSURL URLWithString:kMovieURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.config = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:self.config];
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Success!");
[self populateArray:data];
});
} else {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Received HTTP %ld: %@", (long)httpResponse.statusCode, result);
}
}];
[task resume];
}
- (void) populateArray: (NSData *)data {
NSError *jsonError;
NSDictionary *response =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
if (response) {
self.movieObjects = response[@"movies"];
NSLog(@"The movie objects are: %@", self.movieObjects);
[self.tableView reloadData];
} else {
NSLog(@"ERROR: %@", jsonError);
}
}
The above code is working fine. No questions. However, what I would like to do now is to refactor my code, so instead of having all my network code in a class that contains my delegate methods UITableView
, I want to move the code to a separate class that uses the Singleton method for the best code separation. I have the following skeleton code that looks like this:
#import "Networker.h"
@implementation Networker
+ (NSURLSession *)dataSession {
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
});
return session;
}
+ (void)fetchContentsOfURL:(NSURL *)url completion:(void (^)(NSData *data, NSError *error)) completionHandler {
NSURLSessionDataTask *dataTask = [[self dataSession] dataTaskWithURL:url
completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) {
if (completionHandler == nil) return;
if (error) {
completionHandler(nil, error);
return;
}
completionHandler(data, nil);
}];
[dataTask resume];
}
Singleton . . , " " :
+ (void)fetchContentsOfURL:(NSURL *)url completion:(void (^)(NSData *data, NSError *error)) completionHandler {}
, , "downloadMovieData", "fetchContentsOfURL" NSData
, UITableView , , , "completeHandler" . ?