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

时间:2022-06-29 14:25:36

一、JSON解析数据

 //
// VideoModel.h
// IOS_0130_网络视频
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import <Foundation/Foundation.h> @interface VideoModel : NSObject @property (nonatomic, assign) int id;
@property (nonatomic, assign) int length;
@property (nonatomic, copy) NSString *image;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *url; + (instancetype)videoWithDict:(NSDictionary *)dict; @end //
// VideoModel.m
// IOS_0130_网络视频
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "VideoModel.h" @implementation VideoModel + (instancetype)videoWithDict:(NSDictionary *)dict
{
VideoModel *model = [[VideoModel alloc] init];
[model setValuesForKeysWithDictionary:dict];
return model;
} @end
 //
// VideosTableViewController.m
// IOS_0130_网络视频
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "VideosTableViewController.h"
#import "MBProgressHUD+MJ.h"
#import "UIImageView+WebCache.h"
#import "VideoModel.h"
#import <MediaPlayer/MediaPlayer.h> #define url(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/MJServer/%@",path]] @interface VideosTableViewController () @property (nonatomic, strong) NSMutableArray *arrModel; @end @implementation VideosTableViewController - (void)viewDidLoad {
[super viewDidLoad];
//加载视频信息
[self loadVideo];
}
- (NSMutableArray *)arrModel
{
if (!_arrModel) {
_arrModel = [[NSMutableArray alloc] init];
}
return _arrModel;
} - (void)loadVideo
{
//1.创建NSURL
NSURL *url = url(@"video");
//2.创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError || data == nil) {
[MBProgressHUD showError:@"网络繁忙,请稍后再试"];
return;
}
//解析JSON数据
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSArray *arr = dict[@"videos"]; for (NSDictionary *dict in arr) {
VideoModel *model = [VideoModel videoWithDict:dict]; [self.arrModel addObject:model];
}
[self.tableView reloadData]; }];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.arrModel.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *ID = @"video";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
} VideoModel *model = self.arrModel[indexPath.row]; cell.textLabel.text = model.name; NSString *time = [NSString stringWithFormat:@"时长:%d分钟",model.length];
cell.detailTextLabel.text = time; //显示视频截图 NSURL *url = url(model.image);
[cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1.jpg"]]; return cell;
} - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
VideoModel *model = self.arrModel [indexPath.row]; //创建系统自带的视频播放器
NSURL *url = url(model.url);
MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
//显示视频播放器
[self presentViewController:playerVC animated:nil completion:nil];
} @end

二、XML解析数据

 //
// VideoModel.h
// IOS_0130_网络视频
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import <Foundation/Foundation.h> @interface VideoModel : NSObject @property (nonatomic, assign) int id;
@property (nonatomic, assign) int length;
@property (nonatomic, copy) NSString *image;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *url; + (instancetype)videoWithDict:(NSDictionary *)dict; @end //
// VideoModel.m
// IOS_0130_网络视频
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "VideoModel.h" @implementation VideoModel + (instancetype)videoWithDict:(NSDictionary *)dict
{
VideoModel *model = [[VideoModel alloc] init];
[model setValuesForKeysWithDictionary:dict];
return model;
} @end
 //
// VideosTableViewController.m
// IOS_0130_网络视频
//
// Created by ma c on 16/1/30.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "VideosTableViewController.h"
#import "MBProgressHUD+MJ.h"
#import "UIImageView+WebCache.h"
#import "VideoModel.h"
#import <MediaPlayer/MediaPlayer.h>
#import "GDataXMLNode.h" #define url(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/MJServer/%@",path]] @interface VideosTableViewController ()<NSXMLParserDelegate> @property (nonatomic, strong) NSMutableArray *arrModel; @end @implementation VideosTableViewController /*
IOS中的XML解析方法
1>苹果原生
NSXMLParser:SAX方式解析,使用简单
2>第三方框架
libxml2:纯C语言,默认包含在IOS SDK中,同时支持DOM和SAX方式解析
GDataXML:DOM解析,由Google开发,基于libxml2
3>建议
大文件:NSXMLParser、libxml2
小文件:GDataXML
4>XML解析方式
SAX:一次性将整个XML文档加载进内存,适合解析小文件
DOM:(事件驱动)- 从根元素开始,按顺序一个元素一个元素往下解析,比较适合解析大文件
5>GDataXML常用的类
GDataXMLDocument:代表整个XML文档
GDataXMLElement:代表XML元素 */ - (void)viewDidLoad {
[super viewDidLoad];
//加载视频信息
[self loadVideo];
}
- (NSMutableArray *)arrModel
{
if (!_arrModel) {
_arrModel = [[NSMutableArray alloc] init];
}
return _arrModel;
} - (void)loadVideo
{
//1.创建NSURL
NSURL *url = url(@"video?type=XML");
//2.创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { if (connectionError || data == nil) {
[MBProgressHUD showError:@"网络繁忙,请稍后再试"];
return;
}
//使用GDataXML - 解析XML数据
//[self useGDataXMLWithData:data]; //使用NSXMLParser解析XML数据
[self useNSXMLParserWithData:data];
}];
}
#pragma mark - NSXMLParser解析XML
- (void)useNSXMLParserWithData:(NSData *)data
{
//1.创建XML解析器 - SAX - 逐个往下解析
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
//2.设置代理
parser.delegate = self;
//3.开始解析
[parser parse];
//4.刷新表格
[self.tableView reloadData];
} #pragma mark - NSXMLParser的代理方法
//解析到文档开头是时调用
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//NSLog(@"parserDidStartDocument");
}
//解析到一个元素的开始就会调用
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
{
//NSLog(@"didStartElement------%@",elementName); NSLog(@"attributeDict:%@",attributeDict); if ([elementName isEqualToString:@"videos"]) return; VideoModel *model = [VideoModel videoWithDict:attributeDict];
[self.arrModel addObject:model]; }
//解析到一个元素的结束就会调用
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//NSLog(@"didEndElement------%@",elementName);
}
//解析到文档结尾时调用
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
//NSLog(@"parserDidEndDocument");
} #pragma mark - GDataXML方法
- (void)useGDataXMLWithData:(NSData *)data
{
//解析XML数据
//加载XML文件
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data error:nil]; //获取文档的根元素 -- videos元素
GDataXMLElement *root = doc.rootElement; //获取根元素里面所有video元素
NSArray *elements = [root elementsForName:@"video"]; //遍历所有的video元素
for (GDataXMLElement *videoElement in elements) {
VideoModel *model = [[VideoModel alloc] init]; //取出元素属性
model.id = [videoElement attributeForName:@"id"].stringValue.intValue;
model.length = [videoElement attributeForName:@"length"].stringValue.intValue;
model.name = [videoElement attributeForName:@"name"].stringValue;
model.image = [videoElement attributeForName:@"image"].stringValue;
model.url = [videoElement attributeForName:@"url"].stringValue; //添加到数组中
[self.arrModel addObject:model];
}
//刷新表格
[self.tableView reloadData];
} #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.arrModel.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *ID = @"video";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
} VideoModel *model = self.arrModel[indexPath.row]; cell.textLabel.text = model.name; NSString *time = [NSString stringWithFormat:@"时长:%d分钟",model.length];
cell.detailTextLabel.text = time; //显示视频截图 NSURL *url = url(model.image);
[cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1.jpg"]]; return cell;
} - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
VideoModel *model = self.arrModel [indexPath.row]; //创建系统自带的视频播放器
NSURL *url = url(model.url);
MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
//显示视频播放器
[self presentViewController:playerVC animated:nil completion:nil];
} @end