IOS-网络(JSON解析数据与XML解析数据)
一、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
IOS-网络(JSON解析数据与XML解析数据)的更多相关文章
- IOS 网络浅析-(五 xml解析)
XML 可扩展标记语言 用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言 易读性高,编码手写难度小,数据量大 NSXMLPars ...
- 网络数据的XML解析
网络应用中的数据解析,因为最近的应用,无论是Android的和ios平台的,一直用也是建议用的都是Json解析, xml解析都有点被遗忘了. 然后最近自己在做着玩一个ios的小应用,涉及网络数据的抓取 ...
- Android中级之网络数据解析一之xml解析
本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! --Comic Sans MS Xml解析具有跨平台性,语言无关性,易操作性,因此广受开发者的欢迎. ...
- IOS开发之路三(XML解析之KissXML的使用)
最近再做一个项目需要用到xml的解析.今天查了一些资料自己做了一个小demo.纯OC没有界面.. 在IOS平台上进行XML文档的解析有很多种方法,在SDK里面有自带的解析方法,但是大多情况下都倾向于用 ...
- IOS开发之路三(XML解析之GDataXML的使用)
最近再做一个项目需要用到xml的解析.今天查了一些资料自己做了一个小demo.纯OC没有界面.. 在IOS平台上进行XML文档的解析有很多种方法,在SDK里面有自带的解析方法,但是大多情况下都倾向于用 ...
- IOS网络第二天 - 04-黑酷-GDataXML 解析
****** - (void)viewDidLoad { [super viewDidLoad]; /** 加载服务器最新的视频信息 */ // 1.创建URL NSURL *url = HMUrl( ...
- Oracle表数据转换为XML格式数据
转自:https://blog.csdn.net/smile_caijx/article/details/83352927 使用DBMS_XMLGEN可以解决问题 SELECT DBMS_XMLGEN ...
- iOS网络请求之数据解析
JSON解析 IOS中Json解析的四种方法 NSURLConnection-网络请求浅析 IOS开发:官方自带的JSON使用 XML 解析 GDataXMLNode应用 IOS学习:常用第三方库(G ...
- 2016 - 1- 23 iOS中xml解析 (!!!!!!!有坑要解决!!!!!!)
一: iOS中xml解析的几种方式简介 1.官方原生 NSXMLParser :SAX方式解析,使用起来比较简单 2.第三方框架 libxml2 :纯C 同时支持DOM与SAX GDataXML: D ...
随机推荐
- 一次tns连接错误的解决过程
--同事hadoop连接oracle导入数据,界面报错,后台alert日志报错tns相关错误: **************************************************** ...
- loki之内存池SmallObj[原创]
loki库之内存池SmallObj 介绍 loki库的内存池实现主要在文件smallobj中,顾名思义它的优势主要在小对象的分配与释放上,loki库是基于策略的方法实现的,简单的说就是把某个类通过模板 ...
- Deep Learning(3)算法简介
查看最新论文 Yoshua Bengio, Learning Deep Architectures for AI, Foundations and Trends in Machine Learning ...
- js判断用户是在PC端或移动端访问
js如何判断用户是在PC端和还是移动端访问. 最近一直在忙我们团队的项目“咖啡之翼”,在这个项目中,我们为移动平台提供了一个优秀的体验.伴随Android平台的红火发展.不仅带动国内智能手机行业,而 ...
- 6.1 Controllers -- Introduction
一.Controllers 1. 在Ember.js中,controllers允许你使用展现逻辑装饰你的models.通常,models将会有保存到服务器的属性,然而controllers将会有不需要 ...
- Scrapy:学习笔记(1)——XPath
Scrapy:学习笔记(1)——XPath 1.快速开始 XPath是一种可以快速在HTML文档中选择并抽取元素.属性和文本的方法. 在Chrome,打开开发者工具,可以使用$x工具函数来使用XPat ...
- 尚未指定报表“Report1”的报表定义
在做RDLC项目中遇到这样的错误 本地报表处理期间出错. 尚未指定报表“Report1”的报表定义 未将对象引用设置到对象的实例. 解决方案: 打开reportViewer->LocalRepo ...
- python weekday()函数
def weekday(self): """Return the day of the week as an integer, where Monday is 0 and ...
- gstreamer调试命令
gplay播放命令 gplay 文件全路径 (eg:gplay 123.mp3) gstreamer播放命令 gst-launch playbin2 uri=file:///文件全路径 (eg gs ...
- java fastjson 设置全局输出name最小化
1.通过自定义Filter实现 https://github.com/alibaba/fastjson/wiki/SerializeFilter public class JackJsonLowCas ...