11、AFNetWorking

2017-01-20  本文已影响0人  深爱久随i

一、AFNetWorking简介
AFNetWorking是一个轻量级的网络请求API类库,是以NSURLSession,NSOperation和其他方法为基础的核心代码,可以进行网络请求等操作
在这里我们需要先导入第三方库:

屏幕快照 2017-01-20 上午11.05.26.png

get请求

//get请求的方法
-(void)getMethod{
    //初始化网络会话管理对象
    AFHTTPSessionManager* httpManager=[AFHTTPSessionManager manager];
    //设置请求的响应序列化
//    httpManager.responseSerializer=[AFHTTPResponseSerializer serializer];
    //我们已知返回的数据类型为JSON
    httpManager.responseSerializer=[AFJSONResponseSerializer serializer];
    //根据报错设置响应数据的可接受类型
    httpManager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/plain",@"text/html",@"text/xml",@"application/xml",@"application/json",nil];
    //进行发起get请求
    //第一个参数:网址
    //第二个参数:一般是字典类型,网络请求的参数
    //第三个参数:如果是下载任务,该block中可以监测下载进度
    //第四个参数:网络请求成功会执行的block
    //第五个参数:网络请求失败会执行的block
    //参数字典
    NSDictionary* dic=@{@"date":@"20151101",@"startRecord":@"1",@"len":@"5",@"udid":@"1234567890",@"terminalType":@"Iphone",@"cid":@"213"};
    [httpManager GET:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        //已经下载的资源大小
        NSInteger complete=downloadProgress.completedUnitCount;
        //资源的总大小
        NSInteger total=downloadProgress.totalUnitCount;
        float completeProgress=0;
        if (total) {
            //下载的进度
           completeProgress = complete*1.0/total;
            
        }
         NSLog(@"已经下载的---%ld",(long)complete);
         NSLog(@"总大小---%ld",(long)total);
         NSLog(@"进度为---%ld",(long)completeProgress);
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"网络请求成功");
//        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingAllowFragments) error:nil];
        NSLog(@"---%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"---%@",error.debugDescription);
    }];
}

post请求

//post请求的方法
-(void)postMethod{
    //初始化网络会话管理对象
    AFHTTPSessionManager* httpManager=[AFHTTPSessionManager manager];
    //设置请求的响应序列化
//    httpManager.responseSerializer=[AFHTTPResponseSerializer
//    serializer];
    //我们已知返回的数据类型为JSON
    httpManager.responseSerializer=[AFJSONResponseSerializer serializer];
    //根据报错设置响应数据的可接受类型
    httpManager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/plain"];
     NSDictionary* dic=@{@"date":@"20151101",@"startRecord":@"1",@"len":@"5",@"udid":@"1234567890",@"terminalType":@"Iphone",@"cid":@"213"};
    [httpManager POST:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
       
    
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"网络请求成功");
//        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingAllowFragments) error:nil];
        NSLog(@"---%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"---%@",error.debugDescription);
    }];
}

下载

//downLoad
-(void)downLoadMethod{
    
    //初始化网络会话管理对象
    AFHTTPSessionManager* httpManager=[AFHTTPSessionManager manager];
    //设置请求的响应序列化
    httpManager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSURL* url=[NSURL URLWithString:@"http://www.xiaobuqi.com//d/file/joke/2016-01/1452962161.mp4"];
    NSURLRequest* rq=[NSURLRequest requestWithURL:url];
   NSURLSessionDownloadTask* task= [httpManager downloadTaskWithRequest:rq progress:^(NSProgress * _Nonnull downloadProgress) {
        //已经下载的资源大小
        NSInteger complete=downloadProgress.completedUnitCount;
        //资源的总大小
        NSInteger total=downloadProgress.totalUnitCount;
        float completeProgress=0;
        if (total) {
            //下载的进度
            completeProgress = complete*1.0/total;
            
        }
        NSLog(@"已经下载的---%ld",(long)complete);
        NSLog(@"总大小---%ld",(long)total);
        NSLog(@"进度为---%f",completeProgress);
      
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
       //需要将下载好的资源存储的路径,需要在该block中返回
        NSString* destinationPath=@"/Users/xalo/Desktop/aaa.mp4";
        return [NSURL fileURLWithPath:destinationPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"下载完成");
    }];
    [task resume];
}

监测网络环境

//监测网络环境
-(void)checkNet{
    
   AFNetworkReachabilityManager* reachabilityManager=[AFNetworkReachabilityManager sharedManager];
    //当网络环境发生变化时就会执行该block
    [reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无法连接网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"连接到蜂窝煤网络");
                break;

            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"连接Wifi");
                break;

            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知错误");
                break;
    
            default:
                break;
        }
    }];
    //开始检测
    [reachabilityManager startMonitoring];
    //停止监测网络
//    [reachabilityManager stopMonitoring];
    
}

上一篇下一篇

猜你喜欢

热点阅读