.h
#import <Foundation/Foundation.h>
@interface NetWorkingTool : NSObject
+(void)netWorkingWithURL:(NSString *)strURL block:(void(^)(id result))block;
@end
.m
#import "NetWorkingTool.h"
@implementation NetWorkingTool
+(void)netWorkingWithURL:(NSString *)strURL block:(void (^)(id))block{
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
block(result);
});
}];
[task resume];
}
@end
在ViewController中
先引头文件
#import "NetWorkingTool.h"
在viewDidLoad中用一句话即可实现方法调用,即
[NetWorkingTool netWorkingWithURL:@"http://mrobot.pconline.com.cn/v2/cms/channels/999?pageNo=1&pageSize=20&appVersion=4.4.1" block:^(id result) {
}];
通过填进去一个网址,封装好的工具会给我们传出来一个重要的id类型参数result,我们只需分析传进去的网址的数据结构,考虑用字典/数据来接受这个result,然后再进行对应的数据解析,从而给我们的数据解析工作大大带来了方便,节省了宝贵的时间.
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// Do any additional setup after loading the view.
[self creatData];
}
-(void)creatData{
//获取数据
[NetWorkingTool netWorkingWithURL:@"http://mrobot.pconline.com.cn/v2/cms/channels/999?pageNo=1&pageSize=20&appVersion=4.4.1" block:^(id result) {
//获取articleList里面的数据,存放到articleListArr数组里
NSDictionary *dic = result;
NSArray *articlearr = dic[@"articleList"];
self.articleListArr = [NSMutableArray array];
for (NSDictionary *temp in articlearr) {
articleList *art = [[articleList alloc]init];
[art setValuesForKeysWithDictionary:temp];
[self.articleListArr addObject:art];
[art release];
}
NSArray *focusarr = dic[@"focus"];
self.focusArr = [NSMutableArray array];
for (NSDictionary *temp in focusarr) {
Focus *foc = [[Focus alloc]init];
[foc setValuesForKeysWithDictionary:temp];
[self.focusArr addObject:foc];
[foc release];
}
self.hud.hidden = YES;
[self creatView];
[self.tableView reloadData];
}];
}
网友评论