美文网首页
对AFNetworking的简单封装

对AFNetworking的简单封装

作者: CCSHCoder | 来源:发表于2016-04-12 15:55 被阅读290次

新版 :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);

}];

}

相关文章

网友评论

      本文标题:对AFNetworking的简单封装

      本文链接:https://www.haomeiwen.com/subject/jthwlttx.html