AFNetworking是一个非常方便的网络请求库,可以轻松实现各种网络请求,比如经常使用的GET请求、POST请求,以及上传多张图片等,下面介绍一下基本的使用方法。
-
首先下载AFNetworking 然后在需要使用的类中,导入如下2个头文件:
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
-
GET请求网络数据方式:
-(void)obtainData
{
// 启动系统风火轮
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//前面写服务器给的域名,后面拼接上需要提交的参数,假如参数是key=1
NSString *domainStr = @"http://192.168.1.69/xffcol/index.php/Api/key/1/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//以get的形式提交,只需要将上面的请求地址给GET做参数就可以
[manager GET:domainStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 隐藏系统风火轮
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//json解析
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"---获取到的json格式的字典--%@",resultDic);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}];
}
-
POST请求网络数据方式:
-(void)obtainData
{
// 启动系统风火轮
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//服务器给的域名
NSString *domainStr = @"http://192.168.1.69/xffcol/index.php/Api/";
//假如需要提交给服务器的参数是key=1,class_id=100
//创建一个可变字典
NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
//往字典里面添加需要提交的参数
[parametersDic setObject:@"1" forKey:@"key"];
[parametersDic setObject:@"100" forKey:@"class_id"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//以post的形式提交,POST的参数就是上面的域名,parameters的参数是一个字典类型,将上面的字典作为它的参数
[manager POST:domainStr parameters:parametersDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
// 隐藏系统风火轮
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//json解析
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"---获取到的json格式的字典--%@",resultDic);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}];
}
-
实现上传多张图片:
-(void)uploadPictures{
//域名
NSString *domainStr = @"http://192.168.1.69/xffcol/index.php/Api/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//如果还需要上传其他的参数,参考上面的POST请求,创建一个可变字典,存入需要提交的参数内容,作为parameters的参数提交
[manager POST:domainStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//_imageArray就是图片数组,我的_imageArray里面存的都是图片的data,下面可以直接取出来使用,如果存的是image,将image转换data的方法如下:NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
if (_imageArray.count > 0 ){
for(int i = 0;i < _imageArray.count;i ++){
NSData *data=_imageArray[i];
//上传的参数名
NSString *name = [NSString stringWithFormat:@"%d",i];
//上传的filename
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",name];
[formData appendPartWithFileData:data
name:name
fileName:fileName
mimeType:@"image/jpeg"];
}
}
}success:^(AFHTTPRequestOperation *operation, id responseObject)
{
//关闭系统风火轮
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//json解析
NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"---resultDic--%@",resultDic);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 解析失败
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}];
}
-
设置网络图片的方法:
[leftView setImageWithURL:[NSURL URLWithString:@"http://pic25.nipic.com/20121205/5955207_182136452000__2.jpg"] placeholderImage:@"这里是网络图片还没加载出来的时候,显示的默认图片"];
GET请求
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"这里打印请求成功要做的事"); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@",error); //这里打印错误信息 }];
POST 请求
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSMutableDictionary *parameters = @{@"":@"",@"":@""}; [manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) { } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }];
暂时用的比较多的就这两个,用到其他的 再来更新!!
最近又用到了下载,索性 上传下载都研究了一下 ,补充进来
补充试用AFN3.0下载方法
/**
* AFN3.0 下载
*/
- (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) { //打印下下载进度 WKNSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount); } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) { //下载地址 WKNSLog(@"默认下载地址:%@",targetPath); //设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象 NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; return [NSURL URLWithString:filePath]; } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) { //下载完成调用的方法 WKNSLog(@"下载完成:"); WKNSLog(@"%@--%@",response,filePath); }]; //开始启动任务 [task resume]; }
AFN3.0 上传
/**
* AFN 3.0 上传
* 有两种方式
* upLoad1 和 upLoad2
*/
//第一种方法是通过工程中的文件进行上传
- (void)upLoad1{
//1。创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.上传文件 NSDictionary *dict = @{@"username":@"1234"}; NSString *urlString = @"22222"; [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { //上传文件参数 UIImage *iamge = [UIImage imageNamed:@"123.png"]; NSData *data = UIImagePNGRepresentation(iamge); //这个就是参数 [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) { //打印下上传进度 WKNSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //请求成功 WKNSLog(@"请求成功:%@",responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //请求失败 WKNSLog(@"请求失败:%@",error); }]; } //第二种是通过URL来获取路径,进入沙盒或者系统相册等等 - (void)upLoda2{ //1.创建管理者对象 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //2.上传文件 NSDictionary *dict = @{@"username":@"1234"}; NSString *urlString = @"22222"; [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"file" fileName:@"1234.png" mimeType:@"application/octet-stream" error:nil]; } progress:^(NSProgress * _Nonnull uploadProgress) { //打印下上传进度 WKNSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //请求成功 WKNSLog(@"请求成功:%@",responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { //请求失败 WKNSLog(@"请求失败:%@",error); }]; }
监测当前网络状态(网络监听)
- (void)AFNetworkStatus{
//1.创建网络监测者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
/*枚举里面四个状态 分别对应 未知 无网络 数据 WiFi
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1, 未知
AFNetworkReachabilityStatusNotReachable = 0, 无网络
AFNetworkReachabilityStatusReachableViaWWAN = 1, 蜂窝数据网络
AFNetworkReachabilityStatusReachableViaWiFi = 2, WiFi
};
*/
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//这里是监测到网络改变的block 可以写成switch方便
//在里面可以随便写事件 switch (status) { case AFNetworkReachabilityStatusUnknown: WKNSLog(@"未知网络状态"); break; case AFNetworkReachabilityStatusNotReachable: WKNSLog(@"无网络"); break; case AFNetworkReachabilityStatusReachableViaWWAN: WKNSLog(@"蜂窝数据网"); break; case AFNetworkReachabilityStatusReachableViaWiFi: WKNSLog(@"WiFi网络"); break; default: break; } }] ; }