Attempting to refactor a network method using a Singleton pattern in iOS

My application has the following method that uses NSURLSessionto output movie data from a web service in JSON format:

- (void) downloadMovieData {

    //this is just a visual cue to show that processing is being done
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    //creating the request
    NSURL *url = [NSURL URLWithString:kMovieURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //creating the session
    self.config = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:self.config];

    //the object that makes the call to the web service using the request and the session, and returns a response or an error
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        //At this point a response has been received, so we can turn the indicator off
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

        //I am casting the response to an NSHTTPURLResponse so I can check the status code of the response
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        //a status code of 200 means a successful connection with the web service
        if (httpResponse.statusCode == 200) {

            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Success!");
                //I send the data that was received from the response to the method so that the JSON data is extracted
                [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" . ?

+4
1

, , . , , , .

, .

:

  • , , - , , .
  • , , , , .
+1

Source: https://habr.com/ru/post/1614021/


All Articles