#import <Foundation/Foundation.h>
//给block起 别名
//类型 void(^)(BOOL success , id data)
//别名是 Complicate
typedef void(^Complicate)(BOOL success , id data);
//起别名
typedef NSString * MYString;
@interface DownLoadDataSource : NSObject
//请求 对应url 对应参数dic 的 内容
//通过 complicate 回调 返回 请求到的内容
-(void)downloadWithUrl:(MYString)urlStr parameters:(NSDictionary *)dic complicate:(Complicate) complicate;
@end
#import "DownLoadDataSource.h"
#import "AFNetworking.h"
#define BaseUrl @"http://api.iclient.ifeng.com"//服务器主机地址
@interface DownLoadDataSource()
//用来做请求
@property(nonatomic,strong)AFHTTPRequestOperationManager * manager;
@end
@implementation DownLoadDataSource
-(instancetype)init{
//重写 初始化方法
if (self = [super init]) {
//初始化 请求类
_manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:BaseUrl]];//baseUrl
// _manager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置json解析器
_manager.responseSerializer = [AFJSONResponseSerializer serializer];//设置成json解析器
//设置可以接受的contentTypes
// _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
}
return self;
}
-(void)downloadWithUrl:(MYString)urlStr parameters:(NSDictionary *)dic complicate:(Complicate) complicate{
//发送post请求
[_manager POST:urlStr parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@",operation.response);
//成功之后 通过block 回调
NSError * error = nil;
//解析
// id object = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
if (error) {
if (complicate) {//判断 block变量有没有值
complicate(NO,error);//
}
}else {
if (complicate) {
complicate(YES,responseObject);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
if (complicate) {
complicate(NO,error);
}
NSLog(@"%@",error);
}];
}
@end