AFURLResponseSerialization
的作用是對請求返回的數(shù)據(jù)進行序列化
它有一個序列化的基類AFHTTPResponseSerializer
勘畔,有六個不同的序列化的類繼承于它
-
AFJSONResponseSerializer
JSON格式數(shù)據(jù)響應(yīng) -
AFXMLParserResponseSerializer
iOS端XML數(shù)據(jù)解析響應(yīng) -
AFXMLDocumentResponseSerializer
MAC OS端XML數(shù)據(jù)解析響應(yīng) -
AFPropertyListResponseSerializer
plist格式數(shù)據(jù)解析響應(yīng) -
AFImageResponseSerializer
圖片數(shù)據(jù)解析響應(yīng) -
AFCompoundResponseSerializer
復(fù)合式數(shù)據(jù)解析響應(yīng)
在序列化之前申钩,有一個必要的工作肯适,那就是校驗響應(yīng)是否有效饥悴,在基類AFHTTPResponseSerializer
里面提供了一個核心方法,主要是是校驗響應(yīng)內(nèi)容的類型和狀態(tài)碼
- (BOOL)validateResponse:(NSHTTPURLResponse *)response
data:(NSData *)data
error:(NSError * __autoreleasing *)error
{
BOOL responseIsValid = YES;
NSError *validationError = nil;
if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) {
//如果返回的內(nèi)容類型是不支持的類型,拋出錯誤
if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] &&
!([response MIMEType] == nil && [data length] == 0)) {
if ([data length] > 0 && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]],
NSURLErrorFailingURLErrorKey:[response URL],
AFNetworkingOperationFailingURLResponseErrorKey: response,
} mutableCopy];
if (data) {
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError);
}
responseIsValid = NO;
}
//如果返回的狀態(tài)碼不是200~299哈恰,拋出錯誤
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) {
NSMutableDictionary *mutableUserInfo = [@{
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode],
NSURLErrorFailingURLErrorKey:[response URL],
AFNetworkingOperationFailingURLResponseErrorKey: response,
} mutableCopy];
if (data) {
mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data;
}
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError);
responseIsValid = NO;
}
}
if (error && !responseIsValid) {
*error = validationError;
}
return responseIsValid;
}
其他都是序列化操作晶通,還有初始化方法璃氢,實現(xiàn)NSSecureCoding和NSCopying協(xié)議,這些都是大同小異狮辽,值得一提的是一個圖片加載的分類一也,主要作用是對圖片的解壓,這里可以仔細看下bang's blog喉脖,里面做了比較詳細解釋