YH_HTTPResponseSerializer.m 2.49 KB
//
//  YH_HTTPResponseSerializer.m
//  Yohoboys
//
//  Created by redding on 14-9-18.
//  Copyright (c) 2014年 YOHO. All rights reserved.
//

#import "YH_HTTPResponseSerializer.h"

//NSInteger const YH_HTTPResponseSuccess = 200;           //成功
//NSInteger const YH_HTTPResponseNoAuthority = 400;       //没有权限
//NSInteger const YH_HTTPResponseNotFound = 404;          //传参或无此接口
//NSInteger const YH_HTTPResponseInternalError = 500;     //程序错误

NSString * const YH_HTTPResponseSerializationErrorDomain = @"cn.yoho.error.serialization.response";

typedef NS_ENUM(NSInteger, YH_HTTPResponseStatus) {
    YH_HTTPResponseStatusSuccess = 0,   //成功
    YH_HTTPResponseStatusFailure = 1,   //失败
};

typedef NS_ENUM(NSInteger, YH_HTTPResponseCode) {
    YH_HTTPResponseCodeSuccess = 200000,             //成功
    YH_HTTPResponseCodeNoAuthority = 400000,         //没有权限
    YH_HTTPResponseCodeNotFound = 404000,          //传参或无此接口
    YH_HTTPResponseCodeInternalError = 500000,     //程序错误
};

@implementation YH_HTTPResponseSerializer

#pragma mark - AFURLResponseSerialization

- (id)responseObjectForResponse:(NSURLResponse *)response
                           data:(NSData *)data
                          error:(NSError *__autoreleasing *)error
{
    id responseData;
    
    id responseObject = [super responseObjectForResponse:response data:data error:error];
    
    //获取instagram登录信息的时候特殊处理
    if (responseObject && [responseObject objectForKey:@"meta"]) {
        return responseObject;
    }
    
    //获取杂志列表时需要特殊处理
    if (responseObject && [responseObject objectForKey:@"magazineList"]) {
        return responseObject;
    }
    
    if (responseObject && [responseObject objectForKey:@"status"]) {
        YH_HTTPResponseStatus status = [[responseObject objectForKey:@"status"] integerValue];
        YH_HTTPResponseCode code = [[responseObject objectForKey:@"code"] integerValue];
        
        if (status == YH_HTTPResponseStatusFailure) {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey: [responseObject objectForKey:@"message"],
                                       };
            if (error) {
                *error = [[NSError alloc] initWithDomain:YH_HTTPResponseSerializationErrorDomain code:code userInfo:userInfo];
            }

        }
        else {
            responseData = [responseObject objectForKey:@"data"];
        }
    }
    
    
    
    return responseData;
}


@end