AFNetworking3.1源码解读<三>

上篇文章AFNetworking3.1源码解读<二>主要学习了Request Serialization相关部分,本篇主要学习Response Serialization,AFNetworking中一共实现了6种学习Response Serialization,分别为:AFURLResponseSerialization、AFJSONResponseSerializer、AFXMLParserResponseSerializer、AFPropertyListResponseSerializer、AFImageResponseSerializer和AFCompoundResponseSerializer,我们使用的时候根据自身与服务器协商的数据格式选用相应的Response Serialization即可。

数据合法性检查

合法性检查主要是根据ContentType和StatusCode来判断的,如过接收到的数据的ContentType不在可接受ContentTypeSets中或者HTTP StatusCode不是2xx,则认为数据非法,返回相应NSError,如果出现错误时想要查看RawData则可以通过userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey]来查看。

AFURLResponseSerialization的ContentType=nil,StatusCode为2xx,其子类只改变了ContentType。

AFJSONResponseSerializer可接受的ContentType为:

[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]

AFXMLParserResponseSerializer可接受的ContentType为:

[[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]

AFPropertyListResponseSerializer可接受的ContentType为:

[[NSSet alloc] initWithObjects:@"application/x-plist", nil]

AFImageResponseSerializer可接受的ContentType为:

[[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]

AFCompoundResponseSerializer则由使用者根据自身场景对上述5种ResponseSerializer的组合。

RawData解码

所有的Response Serialization均实现了下面这个接口,该接口返回解码后的数据。

@protocol AFURLResponseSerialization 

- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
                           data:(nullable NSData *)data
                          error:(NSError * _Nullable __autoreleasing *)error

@end

AFURLResponseSerialization解码时不做任何处理,直接返回RawData。
AFJSONResponseSerializer返回JSON格式数据,核心代码如下:

responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];

AFXMLParserResponseSerializer返回XML格式数据,核心代码如下:

[[NSXMLParser alloc] initWithData:data];

AFPropertyListResponseSerializer返回plist格式数据,核心代码如下:

responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];

AFImageResponseSerializer返回UIImage*格式数据,核心代码如下:

if (self.automaticallyInflatesResponseImage) {
        return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale);
    } else {
        return AFImageWithDataAtScale(data, self.imageScale);
    }