子类AFHTTPRequestOperationManager? [英] Subclass AFHTTPRequestOperationManager?

查看:79
本文介绍了子类AFHTTPRequestOperationManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己在整个代码中都使用AFHTTPRequestOperationManager重复了很多代码,因此我正在考虑对其进行子类化,因此我可以将其设置为单例一次,并将所有代码放入子类中,而不是通过我的项目进行传播.但是在AFNetworking 2.0的NSHipster插曲中( http://nshipster.com/afnetworking-2/) ,它说:

I find myself repeating a lot of code using AFHTTPRequestOperationManager throughout my code, so I was thinking about subclassing it, so I can set it up once as a singleton, and put all the code in the subclass, as opposed to have it spread out through my project. However on the NSHipster episode on AFNetworking 2.0 (http://nshipster.com/afnetworking-2/), it says:

2.0中的主要区别在于,出于序列化"部分中说明的原因,您实际上将直接使用此类而不是将其子类化.

The main difference in 2.0 is that you'll actually use this class directly, rather than subclass it, for reasons explained in the "Serialization" section.

由于AFNetworking和NSHipster具有相同的作者,因此我认为这是一个有效的论点.

Since AFNetworking and NSHipster have the same author, I regard this a valid argument.

所以我的问题是,人们将AFHTTPRequestOperationManager子类化以便将大多数网络代码归为一个类,还是在使用框架时忽略了某些内容?

So my question is, do people subclass AFHTTPRequestOperationManager in order to have most network code in one class, or am I overlooking something in the use of the framework?

推荐答案

我有一个连接类的对象.这会将不同的通知广播到可以通过[NSNotificationCenter defaultCenter]注册的任何对象.

I have an object of a connection class. This broadcasts different notifications to any object can register for via [NSNotificationCenter defaultCenter].

-(void) requestData
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kCuriculumDataSourceFetchingStarted object:nil];

    [_sessionManager setDataTaskDidReceiveDataBlock:^(NSURLSession *session,
                                                      NSURLSessionDataTask *dataTask,
                                                      NSData *data)
     {
        if (dataTask.countOfBytesExpectedToReceive == NSURLSessionTransferSizeUnknown)
            return;

        NSUInteger code = [(NSHTTPURLResponse *)dataTask.response statusCode];
        if (!(code> 199 && code < 400))
            return;

        long long  bytesReceived = [dataTask countOfBytesReceived];
        long long  bytesTotal = [dataTask countOfBytesExpectedToReceive];

        NSDictionary *progress = @{@"bytesReceived": @(bytesReceived),
                                   @"bytesTotal":    @(bytesTotal)};

        [[NSNotificationCenter defaultCenter] postNotificationName:kCuriculumDataSourceProgress object:nil userInfo:progress];
    }];



    [self.sessionManager GET:@"recipient/"
                  parameters:nil
                     success:^(NSURLSessionDataTask *task, id responseObject)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kCuriculumDataSourceFetchingSucceeded
                                                            object:nil
                                                          userInfo:@{@"response": responseObject}];
    }
                     failure:^(NSURLSessionDataTask *task, NSError *error)
    {

        NSUInteger code = [(NSHTTPURLResponse *)task.response statusCode];
        NSString *msg;
        switch (code) {
            case kCuriculumDataSourceFetchErrorAPIKeyNotFound:  msg = @"Api Key not found or revoked"; break;
            case kCuriculumDataSourceFetchErrorServerDown:      msg = @"Server Down"; break;
            default:    msg = [error localizedDescription]; break;
        }


        [[NSNotificationCenter defaultCenter] postNotificationName:kCuriculumDataSourceFetchingFailed
                                                            object:nil
                                                          userInfo:@{@"error": msg}];
    }];
}

将接收到的数据写入Core Data的对象将注册kCuriculumDataSourceFetchingSucceeded,并且可以通过notification.userInfo[@"response"]访问接收到的响应.
ViewController将注册kCuriculumDataSourceFetchingSucceededkCuriculumDataSourceFetchingFailedkCuriculumDataSourceProgress.

An object that would write the received data to Core Data would register for kCuriculumDataSourceFetchingSucceeded and can access the received response via notification.userInfo[@"response"].
The ViewController would register for kCuriculumDataSourceFetchingSucceeded, kCuriculumDataSourceFetchingFailed and kCuriculumDataSourceProgress.

我只实例化一个对象,无论它是否为单例,我都不必打扰.因此,我不必继承它的子类,也不必做一些关联的对象技巧来获取将返回单例对象的方法.对从网络获取的数据感兴趣的类将只听通知-他们不必知道获取数据的对象,也不必知道它是否是唯一的对象.

I only instantiate one object, I don't have to bother, if it is an singleton or not. And therefor I don't have to subclass it or do some associated object tricks to get an method that would return the singleton object. Classes interested in the data fetched from network will just listen for the notification — they don't have to know the object that fetched the data and they don't have to know if it is the only of its kind.

连接类对象本身可以注册到其他类将发布以触发新数据提取的通知.

The connection class object itself can register to a notification that other classes would post to trigger a new data fetch.

视图控制器可以注册诸如

A view controller could register for notifications like

-(void)configure
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchingStarted:) name:kCuriculumDataSourceFetchingStarted object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchingSucceeded:) name:kCuriculumDataSourceFetchingSucceeded object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchingFailed:) name:kCuriculumDataSourceFetchingFailed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataSourceProgress:) name:kCuriculumDataSourceProgress object:nil];
}

在这种情况下,视图控制器和网络控制器会导入相同的配置头文件,该文件定义了像kCuriculumDataSourceFetchingSucceeded这样的标记.但是由于它们是普通的NSString,因此可以轻松避免这种依赖性.

In this case the view controller and the network controller import the same configuration header file that defines the tokens like kCuriculumDataSourceFetchingSucceeded. But as these are plain NSStrings, even this dependency can be avoided easily.

用于处理通知的视图控制器方法的示例

An example for a view controllers method that will handle a notification

-(void)dataSourceProgress:(NSNotification *)notification
{
    float bytesReceived = (float)[notification.userInfo[@"bytesReceived"] longLongValue];
    float bytesTotal = (float)[notification.userInfo[@"bytesTotal"] longLongValue];

    float progress = bytesReceived / bytesTotal;

    dispatch_async(dispatch_get_main_queue(), ^{
        self.progressView.progress = progress;
        self.imgView.layer.mask = self.progressView.layer;

    });
}

这篇关于子类AFHTTPRequestOperationManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆