公司的项目在跟服务器交互的时候所有内容都需要加密,也就是说服务器返回的数据全部都要解密之后才能正常使用,可是之前没做过加密,而且AFn自己有一套序列化器,会在接收到服务器的数据时根据自己识别的那几种类型来转换(字典、数组、字符串等),扔给我们的数据是afn已经转换过的数据,而服务器加密之后的数据它根本不识别,最后数据就丢失了,由于项目初期比较紧迫一时没找到afn是在哪里处理接收到服务器的数据的,只好用ASI做请求,但是心里仍然不甘呀,后来项目告一段落又回头找afn处理服务器数据的地方,终于被我找到了:
#import "AFHTTPRequestOperation.h"
- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
// completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
#pragma clang diagnostic ignored "-Wgnu"
self.completionBlock = ^{
if (self.completionGroup) {
dispatch_group_enter(self.completionGroup);
}
dispatch_async(http_request_operation_processing_queue(), ^{
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
id responseObject = self.responseData;//这才是服务器返回的原始数据
//self.responseObject 这个是afn转换之后的数据,原来的afn扔给我们的就是这个数据
NSLog(@"%@",responseObject);
NSData *data = responseObject;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
//转换成nsstring之后解密
NSString *s = [StringEnctypt p_stringDecrypt:str];
NSLog(@"%@",s);
//如果接到服务器的数据是null,自己拼上失败信息 (我们项目里01代表失败)
if (s.length == 0) {
s =@" {\"recode\":\"01\"}";
}
NSError *error = nil;
NSData *da = [s dataUsingEncoding:NSUTF8StringEncoding];
id result = [NSJSONSerialization JSONObjectWithData:da options:NSJSONReadingMutableLeaves error:&error];
NSLog(@"%@",responseObject);
if (self.error) {
if (failure) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(self, self.error);
});
}
} else {
if (success) {
dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{
success(self, result);
});
}
}
}
if (self.completionGroup) {
dispatch_group_leave(self.completionGroup);
}
});
};
#pragma clang diagnostic pop
}