ios - 尝试在 iOS 中使用单例模式重构网络方法

标签 ios objective-c uitableview objective-c-blocks

我的应用程序中有以下方法,它使用 NSURLSession 从 JSON 格式的网络服务中提取电影数据:

- (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);
    }
}

上面的代码运行良好。没有问题。但是,我现在想做的是重构我的代码,而不是将我所有的网络代码都放在包含我的 UITableView 委托(delegate)方法的类中,我想将代码移动到一个单独的类中使用 Singleton 方法更好地分离代码。我有以下框架代码,如下所示:

#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 在我的调用类中。但是,在这样做时,我想确保我了解这个新方法的“completionHandler”部分发生了什么。我该怎么做?

最佳答案

你不能移动它所以它会返回,因为它是异步的。从技术上讲你可以,但你会在等待时阻塞主线程,这很糟糕。

相反,您只需将当前代码替换为对单例的调用,并在完成 block 中调用其他方法来处理数据。

需要注意的几点:

  1. 最好在单例调用某人完成 block 之前将其分派(dispatch)给 main,这样您就不需要该函数的所有用户都记住这样做
  2. 它不需要是单例,您可以在每次需要时实例化该类的副本或使用依赖注入(inject),这两种方法通常都提供更好的架构

关于ios - 尝试在 iOS 中使用单例模式重构网络方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459824/

相关文章:

ios - SpriteKit - SKCameraNode 约束在顶部和底部留有空间

ios - 以编程方式创建的 TableView 的延迟加载单元格图像

ios - 检索在应用程序商店或 iTunes 商店中按给定术语搜索结果的应用程序列表

ios - 捕获并停止传播用户交互 iOS UITableViewCell

ios - 转换倒置的表格 View 单元格中的 3D Touch Peek

ios - 我应该使用核心数据吗?

ios - 为什么状态栏字体大小在 iphone 6 上发生变化?

ios - registerUserNotificationSettings 不显示提示 iOS 8

iphone - 我如何在动画进行时修改 contentInset?

xcode - XCode- objective-c :删除表行崩溃