对AFNetworking的简单封装

2016-04-12  本文已影响290人  CCSHCoder

新版 :AFNetworking 3.X 的二次封装(GET、POST、文件上传、文件下载、超时、HTTPS、请求头、取消网络请求) 

对AFNetworking的简单封装

.h文件

// get请求

+ (void)getWithUrl:(NSString *)url param:(NSDictionary *) param  success:(void (^)(id))success failure:(void (^)(NSError *))failure;

//post请求

+ (void)postWithUrl:(NSString *)url param:(NSDictionary *)param  success:(void (^)(id))success failure:(void (^)(NSError *))failure;

//上传请求

+ (void)postuploading:(NSString *)url param:(NSDictionary *)param  success:(void (^)(id))success failure:(void (^)(NSError *))failure;

.m文件

+ (void)getWithUrl:(NSString *)url param:(NSDictionary *)param  success:(void (^)(id))success failure:(void (^)(NSError *))failure

{

// 1.获得请求管理者

AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 2.发送GET请求

dispatch_async(dispatch_get_main_queue(), ^{

[mgr GET:url parameters:param

success:^(AFHTTPRequestOperation *operation, id responseObj) {

if (success) {

success(responseObj);

}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

if (failure) {

failure(error);

}

}];

});

}

+ (void)postWithUrl:(NSString *)url param:(NSDictionary *)param  success:(void (^)(id))success failure:(void (^)(NSError *))failure

{

// 1.获得请求管理者

AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 2.发送POST请求

dispatch_async(dispatch_get_main_queue(), ^{

[mgr POST:url parameters:param

success:^(AFHTTPRequestOperation *operation, id responseObj) {

if (success) {

success(responseObj);

}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

if (failure) {

failure(error);

}

}];

});

}

+ (void)postuploading:(NSString *)url param:(NSDictionary *)param  success:(void (^)(id))success failure:(void (^)(NSError *))failure{        

// 1.获得请求管理者   

 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];       

 // 2.发送POST请求    

[mgr POST:url parameters:param constructingBodyWithBlock:^(idformData) {

for (int i=0; i<5; i++) {

UIImage *image = [UIImage imageNamed:@"notice_small_bg" ];

NSData *data = UIImageJPEGRepresentation(image, 0.5);

if (data != NULL) {

NSString *name=[NSString stringWithFormat:@"%d-image",i];

NSString *  filePath=[NSString stringWithFormat:@"%d.jpg",i];

[formData appendPartWithFileData:data name:name fileName:filePath mimeType:@"image/jpeg"];

}

}

} success:^(AFHTTPRequestOperation *operation, NSDictionary *statusDict) {

NSLog(@"上传成功%@",statusDict);

for (NSString *str in statusDict) {

NSLog(@"上传成功-----%@",str);

}

//        success(statusDict);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"上传失败");

//        failure(error);

}];

}

上一篇下一篇

猜你喜欢

热点阅读