网络加载数据及单例工具类的代码抽取


 

今天给大家分享一一下网络加载数据:先看代码吧--------------------------


- (void)diseaseNumWithFinishedBlock:(FinishedBlocks)finishedBlock{ NSString *urlStr = @"http://数据接口"; NSDictionary *prama = @{响应参数}; [[NetWorkTool sharedNetWorkTool] POST:urlStr parameters:prama progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"progress"); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:NULL]; NSLog(@"%@----",result); // 取出数组里面的数据 NSDictionary *arrM = result[@"data"]; finishedBlock(arrM); NSLog(@"成功"); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"失败"); }]; }

这里主要用到了block传值,首先先定义一个block,如:

typedef  void(^FinishedBlocks)(NSDictionary * diseaNumWihtFinished);

同时还用到了单例:

 

.h文件中
#import <AFNetworking/AFNetworking.h> @interface NetWorkTool : AFHTTPSessionManager + (instancetype)sharedNetWorkTool; @end

 

.m文件中
static NetWorkTool *_instance; + (instancetype)sharedNetWorkTool{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[NetWorkTool alloc] initWithBaseURL:nil]; _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]; //默认情况下的响应解析方式,就是不管服务器给我们返回的是啥,都按照JSON去解析 //将默认的JSON反序列化方式,改成我们最普通的二进制 _instance.responseSerializer = [AFHTTPResponseSerializer serializer]; //请求的序列化方式默认是纯洁的二进制,改成请求的序列化方式为JSON的二进制 _instance.requestSerializer = [AFJSONRequestSerializer serializer]; }); return _instance; }

 

 然后要给一个属性赋值 ,就要定义一个全局的属性来接收它,这样就得到你想要的结果! 当你如果获取不到网络加载的值时一定要静下心想一想自己的思路,任何一种可能都要去尝试,因为只有在不断的验证你才能知道自己所需要的实现的功能。今天就到这里吧。欢迎大家有问题交流哦嘿嘿-------❤️❤️❤️

posted @ 2016-01-24 23:45  Ruby_Hua  阅读(199)  评论(0编辑  收藏  举报