CORE(核心):
HTTP CLIENT :
AFHTTPClient : 是一个封装了基于http协议的网络应用程序的公共交流模式
IMAGES
注意事项 :
示例代码 :
get请求:
//GET请求
- (void)afGetMethod {
//网络请求的核心类,http请求的会话管理对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//设置响应数据的格式
//AFHTTPResponseSerializer 返回的数据类型为二进制类型
//AFJSONResponseSerializer 返回数据类型为json类型
//AFXMLParserResponseSerializer xml类型
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//get请求
//第一个参数:请求网址
//第二个参数:请求参数
//第三个参数:下载进度
//第四个参数:请求成功的block回调
//第五个参数:数据请求失败
[manager GET:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151031&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// NSLog(@"----------%@",responseObject);//所需要的数据
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
NSLog(@"%@",[NSThread currentThread]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}];
}
post请求:
//post请求
- (void)afPostMethd {
//会话管理对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//设置返回数据的格式
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//转义字符
// NSString *dict1 = @"{\\"data\\":20151031,\\"startRecord\\":1,\\"len\\":5,\\"udid\\":1234567890,\\"terminalType\\":\\"Iphone\\",\\"cid\\":213}";
NSDictionary *dict = @{@"data":@"20151031",@"startRecord":@"1",@"len":@"5",@"udid":@"1234567890",@"terminalType":@"Iphone",@"cid":@"213"};
//对象类型转json串
// NSData *strData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
// NSString *jsonStr = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
// NSLog(@"%%");
//constructingBodyWithBlock:在此block种可以为上传的参数添加(拼接)新的需要的上传的数据,适用于上传给服务器的数据流比较大的时候
//af中一般post请求的参数都为字典类型
[manager POST:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" parameters:dict constructingBodyWithBlock:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"-------------***%@",str);
NSLog(@"%@",[NSThread currentThread]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}];
}
网络监测 :
AppDelegate.m文件中
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//开始监测
[manager startMonitoring];
//网络状态的返回
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//当网络发生变化的时候,我们发送通知,告知需要此消息的对象
[[NSNotificationCenter defaultCenter] postNotificationName:kNetStatus object:@(status)];
}];
ViewController.m文件中
//添加一个观察者,观察网络的变化
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netChange:) name:kNetStatus object:nil];
//通知的回调方法
- (void)netChange:(NSNotification*)notification {
//取出网络状态
AFNetworkReachabilityStatus status = [notification.object intValue];
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知状态");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"无网络连接");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"3G/4G");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"WiFi");
break;
default:
break;
}
}
上传与下载
#pragma mark - 上传
//有两种方式
//第一种方法是通过工程中的文件进行上传
- (void)upLoad1 {
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.上传文件
NSDictionary *dict = @{@"username":@"1234"};
//上传至哪个url
NSString *url = @"1235466";
[manager POST:url parameters:dict constructingBodyWithBlock:^(id _Nonnull formData) {
//上传文件参数
UIImage *image = [UIImage imageNamed:@"4.png"];
NSData *data = UIImagePNGRepresentation(image);
//这个就是参数
[formData appendPartWithFileData:data name:@"file" fileName:@"4.png" mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
//打印上传进度
NSLog(@"%lf",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}];
}
//第二种:是通过url来获取路径,进入沙盒或者系统相册等等
- (void)upload2 {
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.上传文件
NSDictionary *dic = @{@"userName":@"123456"};
NSString *urlString = @"456789";
[manager POST:urlString parameters:dic constructingBodyWithBlock:^(id _Nonnull formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"fileName" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%lf",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功: %@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败: %@",error);
}];
}
#pragma mark - 下载
- (void)downLoad {
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.确定请求的URL地址
NSURL *url = [NSURL URLWithString:@""];
//3.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//打印下载进度
NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//下载地址
NSLog(@"默认下载地址 : %@",targetPath);
//设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
return [NSURL URLWithString:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//下载完成调用的方法
NSLog(@"下载完成");
NSLog(@"%@--%@",response,filePath);
}];
//开始启动任务
[task resume];
}