IOS-网络(JSON解析数据与XML解析数据)

一、JSON解析数据

 1 //
 2 //  VideoModel.h
 3 //  IOS_0130_网络视频
 4 //
 5 //  Created by ma c on 16/1/30.
 6 //  Copyright © 2016年 博文科技. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 @interface VideoModel : NSObject
12 
13 @property (nonatomic, assign) int id;
14 @property (nonatomic, assign) int length;
15 @property (nonatomic, copy) NSString *image;
16 @property (nonatomic, copy) NSString *name;
17 @property (nonatomic, copy) NSString *url;
18 
19 + (instancetype)videoWithDict:(NSDictionary *)dict;
20 
21 @end
22 
23 //
24 //  VideoModel.m
25 //  IOS_0130_网络视频
26 //
27 //  Created by ma c on 16/1/30.
28 //  Copyright © 2016年 博文科技. All rights reserved.
29 //
30 
31 #import "VideoModel.h"
32 
33 @implementation VideoModel
34 
35 + (instancetype)videoWithDict:(NSDictionary *)dict
36 {
37     VideoModel *model = [[VideoModel alloc] init];
38     [model setValuesForKeysWithDictionary:dict];
39     return model;
40 }
41 
42 @end
  1 //
  2 //  VideosTableViewController.m
  3 //  IOS_0130_网络视频
  4 //
  5 //  Created by ma c on 16/1/30.
  6 //  Copyright © 2016年 博文科技. All rights reserved.
  7 //
  8 
  9 #import "VideosTableViewController.h"
 10 #import "MBProgressHUD+MJ.h"
 11 #import "UIImageView+WebCache.h"
 12 #import "VideoModel.h"
 13 #import <MediaPlayer/MediaPlayer.h>
 14 
 15 #define url(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/MJServer/%@",path]]
 16 
 17 @interface VideosTableViewController ()
 18 
 19 @property (nonatomic, strong) NSMutableArray *arrModel;
 20 
 21 @end
 22 
 23 @implementation VideosTableViewController
 24 
 25 - (void)viewDidLoad {
 26     [super viewDidLoad];
 27     //加载视频信息
 28     [self loadVideo];
 29 }
 30 - (NSMutableArray *)arrModel
 31 {
 32     if (!_arrModel) {
 33         _arrModel = [[NSMutableArray alloc] init];
 34     }
 35     return _arrModel;
 36 }
 37 
 38 - (void)loadVideo
 39 {
 40     //1.创建NSURL
 41     NSURL *url = url(@"video");
 42     //2.创建请求
 43     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 44     //3.发送请求
 45     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
 46         if (connectionError || data == nil) {
 47             [MBProgressHUD showError:@"网络繁忙,请稍后再试"];
 48             return;
 49         }
 50         //解析JSON数据
 51         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
 52         NSArray *arr = dict[@"videos"];
 53         
 54         for (NSDictionary *dict in arr) {
 55             VideoModel *model = [VideoModel videoWithDict:dict];
 56             
 57             [self.arrModel addObject:model];
 58         }
 59         [self.tableView reloadData];
 60         
 61     }];
 62 }
 63 
 64 - (void)didReceiveMemoryWarning {
 65     [super didReceiveMemoryWarning];
 66     // Dispose of any resources that can be recreated.
 67 }
 68 
 69 #pragma mark - Table view data source
 70 
 71 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 72     return self.arrModel.count;
 73 }
 74 
 75 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 76     NSString *ID = @"video";
 77     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
 78     
 79     if (!cell) {
 80         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
 81     }
 82     
 83     VideoModel *model = self.arrModel[indexPath.row];
 84     
 85     cell.textLabel.text = model.name;
 86     
 87     NSString *time = [NSString stringWithFormat:@"时长:%d分钟",model.length];
 88     cell.detailTextLabel.text = time;
 89     
 90     //显示视频截图
 91     
 92     NSURL *url = url(model.image);
 93     [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1.jpg"]];
 94     
 95     return cell;
 96 }
 97 
 98 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 99 {
100     VideoModel *model = self.arrModel [indexPath.row];
101     
102     //创建系统自带的视频播放器
103     NSURL *url = url(model.url);
104     MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
105     //显示视频播放器
106     [self presentViewController:playerVC animated:nil completion:nil];
107 }
108 
109 
110 
111 @end

二、XML解析数据

 1 //
 2 //  VideoModel.h
 3 //  IOS_0130_网络视频
 4 //
 5 //  Created by ma c on 16/1/30.
 6 //  Copyright © 2016年 博文科技. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 @interface VideoModel : NSObject
12 
13 @property (nonatomic, assign) int id;
14 @property (nonatomic, assign) int length;
15 @property (nonatomic, copy) NSString *image;
16 @property (nonatomic, copy) NSString *name;
17 @property (nonatomic, copy) NSString *url;
18 
19 + (instancetype)videoWithDict:(NSDictionary *)dict;
20 
21 @end
22 
23 
24 //
25 //  VideoModel.m
26 //  IOS_0130_网络视频
27 //
28 //  Created by ma c on 16/1/30.
29 //  Copyright © 2016年 博文科技. All rights reserved.
30 //
31 
32 #import "VideoModel.h"
33 
34 @implementation VideoModel
35 
36 + (instancetype)videoWithDict:(NSDictionary *)dict
37 {
38     VideoModel *model = [[VideoModel alloc] init];
39     [model setValuesForKeysWithDictionary:dict];
40     return model;
41 }
42 
43 @end
  1 //
  2 //  VideosTableViewController.m
  3 //  IOS_0130_网络视频
  4 //
  5 //  Created by ma c on 16/1/30.
  6 //  Copyright © 2016年 博文科技. All rights reserved.
  7 //
  8 
  9 #import "VideosTableViewController.h"
 10 #import "MBProgressHUD+MJ.h"
 11 #import "UIImageView+WebCache.h"
 12 #import "VideoModel.h"
 13 #import <MediaPlayer/MediaPlayer.h>
 14 #import "GDataXMLNode.h"
 15 
 16 #define url(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/MJServer/%@",path]]
 17 
 18 @interface VideosTableViewController ()<NSXMLParserDelegate>
 19 
 20 @property (nonatomic, strong) NSMutableArray *arrModel;
 21 
 22 @end
 23 
 24 @implementation VideosTableViewController
 25 
 26 /*
 27  IOS中的XML解析方法
 28  1>苹果原生
 29    NSXMLParser:SAX方式解析,使用简单
 30  2>第三方框架
 31    libxml2:纯C语言,默认包含在IOS SDK中,同时支持DOM和SAX方式解析
 32    GDataXML:DOM解析,由Google开发,基于libxml2
 33  3>建议
 34    大文件:NSXMLParser、libxml2
 35    小文件:GDataXML
 36  4>XML解析方式
 37    SAX:一次性将整个XML文档加载进内存,适合解析小文件
 38    DOM:(事件驱动)- 从根元素开始,按顺序一个元素一个元素往下解析,比较适合解析大文件
 39  5>GDataXML常用的类
 40    GDataXMLDocument:代表整个XML文档
 41    GDataXMLElement:代表XML元素
 42  
 43  */
 44 
 45 - (void)viewDidLoad {
 46     [super viewDidLoad];
 47     //加载视频信息
 48     [self loadVideo];
 49 }
 50 - (NSMutableArray *)arrModel
 51 {
 52     if (!_arrModel) {
 53         _arrModel = [[NSMutableArray alloc] init];
 54     }
 55     return _arrModel;
 56 }
 57 
 58 - (void)loadVideo
 59 {
 60     //1.创建NSURL
 61     NSURL *url = url(@"video?type=XML");
 62     //2.创建请求
 63     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 64     //3.发送请求
 65     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
 66         
 67         if (connectionError || data == nil) {
 68             [MBProgressHUD showError:@"网络繁忙,请稍后再试"];
 69             return;
 70         }
 71         //使用GDataXML - 解析XML数据
 72         //[self useGDataXMLWithData:data];
 73         
 74         //使用NSXMLParser解析XML数据
 75         [self useNSXMLParserWithData:data];
 76     }];
 77 }
 78 #pragma mark - NSXMLParser解析XML
 79 - (void)useNSXMLParserWithData:(NSData *)data
 80 {
 81     //1.创建XML解析器 - SAX - 逐个往下解析
 82     NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
 83     //2.设置代理
 84     parser.delegate = self;
 85     //3.开始解析
 86     [parser parse];
 87     //4.刷新表格
 88     [self.tableView reloadData];
 89 }
 90 
 91 #pragma mark - NSXMLParser的代理方法
 92 //解析到文档开头是时调用
 93 - (void)parserDidStartDocument:(NSXMLParser *)parser
 94 {
 95     //NSLog(@"parserDidStartDocument");
 96 }
 97 //解析到一个元素的开始就会调用
 98 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
 99 {
100     //NSLog(@"didStartElement------%@",elementName);
101     
102     NSLog(@"attributeDict:%@",attributeDict);
103     
104     if ([elementName isEqualToString:@"videos"])  return;
105     
106     VideoModel *model = [VideoModel videoWithDict:attributeDict];
107     [self.arrModel addObject:model];
108 
109 }
110 //解析到一个元素的结束就会调用
111 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
112 {
113     //NSLog(@"didEndElement------%@",elementName);
114 }
115 //解析到文档结尾时调用
116 - (void)parserDidEndDocument:(NSXMLParser *)parser
117 {
118     //NSLog(@"parserDidEndDocument");
119 }
120 
121 #pragma mark - GDataXML方法
122 - (void)useGDataXMLWithData:(NSData *)data
123 {
124     //解析XML数据
125     //加载XML文件
126     GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data error:nil];
127     
128     //获取文档的根元素 -- videos元素
129     GDataXMLElement *root = doc.rootElement;
130     
131     //获取根元素里面所有video元素
132     NSArray *elements = [root elementsForName:@"video"];
133     
134     //遍历所有的video元素
135     for (GDataXMLElement *videoElement in elements) {
136         VideoModel *model = [[VideoModel alloc] init];
137         
138         //取出元素属性
139         model.id = [videoElement attributeForName:@"id"].stringValue.intValue;
140         model.length = [videoElement attributeForName:@"length"].stringValue.intValue;
141         model.name = [videoElement attributeForName:@"name"].stringValue;
142         model.image = [videoElement attributeForName:@"image"].stringValue;
143         model.url = [videoElement attributeForName:@"url"].stringValue;
144         
145         //添加到数组中
146         [self.arrModel addObject:model];
147     }
148     //刷新表格
149     [self.tableView reloadData];
150 }
151 
152 #pragma mark - Table view data source
153 
154 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
155     return self.arrModel.count;
156 }
157 
158 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
159     NSString *ID = @"video";
160     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
161     
162     if (!cell) {
163         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
164     }
165     
166     VideoModel *model = self.arrModel[indexPath.row];
167     
168     cell.textLabel.text = model.name;
169     
170     NSString *time = [NSString stringWithFormat:@"时长:%d分钟",model.length];
171     cell.detailTextLabel.text = time;
172     
173     //显示视频截图
174     
175     NSURL *url = url(model.image);
176     [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1.jpg"]];
177     
178     return cell;
179 }
180 
181 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
182 {
183     VideoModel *model = self.arrModel [indexPath.row];
184     
185     //创建系统自带的视频播放器
186     NSURL *url = url(model.url);
187     MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
188     //显示视频播放器
189     [self presentViewController:playerVC animated:nil completion:nil];
190 }
191 
192 
193 
194 @end
原文地址:https://www.cnblogs.com/oc-bowen/p/5171155.html