AFNetworking的二次封装

//
//  NetWorkingManager.h
//  PowerBank
//
//  Created by 麦鱼科技 on 2017/7/11.
//  Copyright © 2017年 麦鱼科技. All rights reserved.
//

#import 
#import 

/**
 成功的block

 @param response 返回数据
 */
typedef void(^Succeed)(id response);


/**
 失败的block

 @param error 错误信息
 */
typedef void(^Failed)(NSError *error);

@interface NetWorkingManager : NSObject

+ (NetWorkingManager *)shared;

/**
 post请求

 @param url url
 @param params 参数
 @param succeed 成功返回
 @param failed 失败返回
 */
- (void)postWithUrl:(NSString *)url params:(NSDictionary*)params succeed:(Succeed)succeed failed:(Failed)failed;

/**
 get请求

 @param url url
 @param params 参数
 @param succeed 成功
 @param failed 失败
 */
- (void)getWithUrl:(NSString *)url params:(NSDictionary*)params succeed:(Succeed)succeed failed:(Failed)failed;

@end
//
//  NetWorkingManager.m
//  PowerBank
//
//  Created by 麦鱼科技 on 2017/7/11.
//  Copyright © 2017年 麦鱼科技. All rights reserved.
//

#import "NetWorkingManager.h"

#define BASE_URL @""

static NetWorkingManager *manager = nil;

static AFHTTPSessionManager *afManager = nil;

@implementation NetWorkingManager

+ (NetWorkingManager *)shared{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NetWorkingManager alloc]init];
        afManager = [AFHTTPSessionManager manager];
        afManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    });
    return manager;
}

- (void)postWithUrl:(NSString *)url params:(NSDictionary *)params succeed:(Succeed)succeed failed:(Failed)failed{
    
    NSString *newUrl = [BASE_URL stringByAppendingString:url];
    [afManager POST:newUrl parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            succeed(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed(error);
    }];
}

- (void)getWithUrl:(NSString *)url params:(NSDictionary *)params succeed:(Succeed)succeed failed:(Failed)failed{
    
    NSString *newUrl = [BASE_URL stringByAppendingString:url];
    [afManager GET:newUrl parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            succeed(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed(error);
    }];
}

@end

你可能感兴趣的:(AFNetworking的二次封装)