介绍
AFNetworking是对NSURLConnection和NSURLSession的进一步封装,现在使用广泛,在AFN3.0之后,舍弃了对NSURLConnection的封装。
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"aa");
//[self get_connection];
//[self get_session];
// [self post_connection];
[self post_session];
NSLog(@"aa");
}
-(void)post_session{
//定义一个管理器
AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
//设置响应序列化
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
NSDictionary *dict=@{@"grade_id":@"2"};
[manager POST: @"http://new.api.bandu.cn/book/listofgrade" parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
//二进制数据转换成JSON数据
id objc=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(@"objc=%@",objc);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error:%@",error);
}];
}
-(void)post_connection{
//区别就是GET和POST的一字之差
//定义一个管理器
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
/*
AFHTTPResponseSerializer 响应收到的数据s就是二进制数据
AFJSONResponseSerializer JSON数据
AFXMLParserResponseSerializer XML数据
*/
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
//发送请求,parameters字典类型,success请求成功的回调,failure请求失败的回调
//序列化:响应序列化和请求序列化,响应序列化默认是json类型的
NSDictionary *dict=@{@"grade_id":@"2"};
[manager POST:@"http://new.api.bandu.cn/book/listofgrade" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
//operation 代表响应头的信息
//responseObject 代表的是响应体
NSLog(@"success--%@--%@",operation,responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"error:%@",error);
}];
}
-(void)get_session{
//定义一个管理器
AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
//设置响应序列化
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
NSDictionary *dict=@{@"grade_id":@"2"};
[manager GET: @"http://new.api.bandu.cn/book/listofgrade" parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
//二进制数据转换成JSON数据
id objc=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSLog(@"objc=%@",objc);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error:%@",error);
}];
}
-(void)get_connection{
//定义一个管理器
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
/*修改响应序列化,响应回来的3种数据
AFHTTPResponseSerializer 响应收到的数据就是二进制数据
AFJSONResponseSerializer JSON数据
AFXMLParserResponseSerializer XML数据
*/
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
//发送请求,parameters字典类型,success请求成功的回调,failure请求失败的回调
//序列化:响应序列化和请求序列化,响应序列化默认是json类型的
NSDictionary *dict=@{@"grade_id":@"2"};
[manager GET:@"http://new.api.bandu.cn/book/listofgrade" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
//operation 代表响应头的信息
//responseObject 代表的是响应体
NSLog(@"success--%@--%@",operation,responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"error:%@",error);
}];
}
@end
AFNetworking对post请求和get请求的封装,一字之差。
对connection和session的封装,管理器不一样。
常用类和方法:
下载任务和进度监测
#import "ViewController.h"
#import "AFNetWorking.h"
#define IMAGE_URL @"http://www.zt5.com/uploadfile/2019/0127/20190127010113674.jpg"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//定义一个管理器
AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
//下载任务
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString: IMAGE_URL]];
//定义一个用于监测进度的NSProgress类
NSProgress *progress=nil;
/*
@property int64_t totalUnitCount;//总共的
@property int64_t completedUnitCount;下载的数据长度
*/
//targetPath下载的文件的保存地址,responsex响应头
NSURLSessionDownloadTask *task= [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
// NSLog(@"--%@",targetPath);
//返回一个你想下载的文件放置的位置,是否返回一个完整的路径,YES;stringByAppendingPathComponent拼一个路径;response.suggestedFilename建议的路径。 沙盒的操作
//数组要用lastobject等指定对象
NSString *location=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:response.suggestedFilename];
//NSLog(@"%@",[NSURL fileURLWithPath:location]);
//返回的是NSURL格式
return [NSURL fileURLWithPath:location];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
// NSLog(@"--filepath%@",filePath);
// NSLog(@"--error=%@",error);
}];
//使用KVO检测进度?什么是KVO,forKeyPath检测的数据。
//任务之前progress是nil,所以监测要放到任务之后添加。
[progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
//开启任务
[task resume];
}
//ofObject检测的对象
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
NSProgress *progress=(NSProgress *)object;
NSLog(@"%f",1.0*progress.completedUnitCount/progress.totalUnitCount);
}
@end
网络监测
用AFNetworking监测
-(void)AFReachability{
//监测网络状态
AFNetworkReachabilityManager *manager=[AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
/*
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1,未知网络
AFNetworkReachabilityStatusNotReachable = 0,没有连接网络
AFNetworkReachabilityStatusReachableViaWWAN = 1,手机网络
AFNetworkReachabilityStatusReachableViaWiFi = 2,wifi
*/
NSLog(@"--status=%zd",status);
}];
//开启网络监测
[manager startMonitoring];
}
用reachability监测
#import "ViewController.h"
#import "AFNetworking.h"
#import "Reachability.h"
@interface ViewController ()
@property (nonatomic,strong) Reachability *reach;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//监听通知,网络发生变化时执行selector的方法
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeReachability) name:kReachabilityChangedNotification object:nil];
[self reachability];
}
-(void)reachability{
/*
typedef NS_ENUM(NSInteger, NetworkStatus) {
// Apple NetworkStatus Compatible Names.
NotReachable = 0,
ReachableViaWiFi = 2,
ReachableViaWWAN = 1
};
*/
//开启网络监控
self.reach=[Reachability reachabilityForInternetConnection];
[self.reach startNotifier];
}
-(void)changeReachability{
if(self.reach.currentReachabilityStatus==NotReachable){
NSLog(@"没有网络");
}else if(self.reach.currentReachabilityStatus==ReachableViaWiFi){
NSLog(@"WIFI");
}else{
NSLog(@"手机网络");
}
}