IOS开发超棒文集iOS自学之路

拿走即用之afn封装(OC版)

2016-05-10  本文已影响2294人  鹿丸眼中的云

afn封装

.h文件

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, RequestMethod)
{
    post,
    get
};

@interface NetworkTools : NSObject

+ (instancetype)shareNetworkTools;

/**
 * requestMethod:请求方式
 * urlString:请求地址
 * parameters:请求参数
 * responseBlock:请求成功或失败的回调
 */

- (void)requestWithMethod:(RequestMethod)requestMethod andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock;

/**
 * data:上传资料
 * name:上传资料的名字
 * urlString:请求地址
 * parameters:请求参数
 * responseBlock:请求成功或失败的回调
 */

- (void)requestWithData:(NSData *)data andName:(NSString *)name andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock;

@end

.m文件

#import "NetworkTools.h"
#import <AFNetworking.h>

@implementation NetworkTools

+ (instancetype)shareNetworkTools
{
    static NetworkTools *networkTools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        networkTools = [[NetworkTools alloc] init];
    });
    return networkTools;
}

- (void)requestWithMethod:(RequestMethod)requestMethod andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock
{
    // 定义成功的block
    void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
    {
        responseBlock(responseObject, nil);
    };
    // 定义失败的block
    void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
    {
        responseBlock(nil, error);
    };
    if (requestMethod == get) {
        [[AFHTTPSessionManager manager] GET:urlString parameters:parameters success:success failure:failure];
    } else {
        [[AFHTTPSessionManager manager] POST:urlString parameters:parameters success:success failure:failure];
    }
}

- (void)requestWithData:(NSData *)data andName:(NSString *)name andUrlString:(NSString *)urlString andParameters:(id) parameters andFinished:(void(^)(id response, NSError *error))responseBlock
{
    void (^success)(NSURLSessionDataTask *dataTask, id responseObject) = ^(NSURLSessionDataTask *dataTask,id responseObject)
    {
        responseBlock(responseObject, nil);
    };
    void (^failure)(NSURLSessionDataTask *dataTask,NSError *error) = ^(NSURLSessionDataTask *dataTask,NSError *error)
    {
        responseBlock(nil, error);
    };
    [[AFHTTPSessionManager manager] POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:name fileName:@"aa" mimeType:@"application/octet-stream"];
    } success:success failure:failure];
}

@end
上一篇下一篇

猜你喜欢

热点阅读