分类: IOS2014-06-30 20:33 471人阅读 评论(3) 收藏 举报
  1. #import "MainViewController.h"
  2. #import "Video.h"
  3. #define kBaseURL @"http://192.168.3.252/~apple"
  4. @interface MainViewController ()<UITableViewDataSource, UITableViewDelegate>
  5. @property (strong, nonatomic) NSArray *dataList;
  6. @property (weak, nonatomic) UITableView *tableView;
  7. @end
  8. @implementation MainViewController
  1. </pre><p class="p1">/*</p><p class="p2"><span class="s1"> </span>在网络应用开发中,</p><p class="p2"><span class="s1"> 1 </span>数据是同步加载的,可以保证用户有的看</p><p class="p2"><span class="s1"> 2 </span>图像,音频,视频是异步加载的。可以保证在不阻塞主线程的使用的前提下,用户可以渐渐的看到多媒体信息。</p><p class="p1"> */</p><pre code_snippet_id="412158" snippet_file_name="blog_20140630_1_3481337" name="code" class="objc">
  2. #pragma mark 实例化视图
  3. - (void)loadView
  4. {
  5. self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
  6. //1 tableview
  7. CGRect frame = self.view.bounds;
  8. UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 44) style:UITableViewStylePlain];
  9. //1)数据源
  10. [tableView setDataSource:self];
  11. //2)代理
  12. [tableView setDelegate:self];
  13. //)设置表格高度
  14. [tableView setRowHeight:80];
  15. [self.view addSubview:tableView];
  16. self.tableView = tableView;
  17. //toolBar
  18. UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, tableView.bounds.size.height, 320, 44)];
  19. [self.view addSubview:toolBar];
  20. //添加toolbar按钮
  21. UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:@"load json" style:UIBarButtonItemStyleDone target:self action:@selector(loadJson)];
  22. UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"load xml" style:UIBarButtonItemStyleDone target:self action:@selector(loadXML)];
  23. UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
  24. [toolBar setItems:@[item3, item1, item3, item2, item3]];
  25. }
  26. #pragma mark -uitableview数据源方法  对于uitableview下面这两个方法是必须实现的。
  27. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  28. {
  29. return self.dataList.count;
  30. }
  31. //每填充一行都调用一次这个方法。知道界面上的所有行都填充完毕。,
  32. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  33. {
  34. //使用可充用标示符查询可重用单元格
  35. static NSString *ID = @"MyCell";
  36. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
  37. if (cell == nil) {
  38. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
  39. }
  40. //设置单元格内容
  41. Video *v = self.dataList[indexPath.row];
  42. cell.textLabel.text = v.name;
  43. cell.detailTextLabel.text = v.teacher;
  44. //加载图片
  45. //1)同步加载网络图片,同步方法以为这这些指令在完成之前,后续指令都无法执行。
  46. //注意:在开发网络应用时,不要使用同步方法加载图片,否则会严重影响用户体验
  47. //    NSString *imagePath = [NSString stringWithFormat:@"%@%@", kBaseURL, v.imageURL];
  48. //    NSURL *imageUrl = [NSURL URLWithString:imagePath];
  49. //    NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
  50. //    UIImage *image = [UIImage imageWithData:imageData];
  51. //
  52. //    //2)异步加载网络图片
  53. //    //网络连接本身就有异步命令 sendAsync
  54. //    [cell.imageView setImage:image];
  55. //如果缓存图像不存在
  56. if (v.cacheImage == nil) {
  57. //使用默认图像占位,即能够保证有图像,又能够保证有地方。
  58. UIImage *image = [UIImage imageNamed:@"user_default.png"];
  59. [cell.imageView setImage:image]; //使用默认图像占位
  60. //开启异步连接,加载图像,因为加载完成之后,需要刷新对应的表格航
  61. [self loadImageAsyncWithIndexPath:indexPath];
  62. }else
  63. {
  64. [cell.imageView setImage:v.cacheImage];
  65. }
  66. //[self loadImageAsyncWithUrl:imageUrl imageView:cell.imageView];
  67. return cell;
  68. }
  69. #pragma mark 异步加载网络图片
  70. //由于uitableview是可重用的,为了避免用户快速频繁刷新表格,造成数据冲突,不能直接将uiimageview传入异步方法
  71. //正确的解决方法是:将表格行的indexpath传入异步方法,加载完成图像以后,直接刷新指定的行。
  72. - (void)loadImageAsyncWithIndexPath:(NSIndexPath *)indexPath
  73. {
  74. Video *v = self.dataList[indexPath.row]; //取出当前要填充的行
  75. NSString *imagePath = [NSString stringWithFormat:@"%@%@", kBaseURL, v.imageURL];
  76. NSURL *imageUrl = [NSURL URLWithString:imagePath];
  77. //NSLog(@"%@ %@", url, imageView);
  78. //1 request
  79. NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
  80. //2 connection sendasync异步请求
  81. [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
  82. //UIImage *image = [UIImage imageWithData:data];
  83. //[imageView setImage:image];
  84. //将网络数据保存至缓存图像。
  85. v.cacheImage = [UIImage imageWithData:data];
  86. //刷新表格
  87. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
  88. }];
  89. }
  90. #pragma mark 处理json数据
  91. - (void)handlerJSONData:(NSData *)data
  92. {
  93. //json文件中的[]表示一个数据。
  94. //反序列化json数据
  95. /*
  96. 序列化: 将一个nsboject转换成序列数据,以便通过互联网进行传输。
  97. 反序列化:将网络上获取的数据反向生成我们需要的对象。
  98. */
  99. //第二个参数是解析方式,一般用NSJSONReadingAllowFragments
  100. NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
  101. NSLog(@"%@", array);  //json解析以后是nsarray格式的数据。
  102. //提示:如果开发网络应用,可以将反序列化出来的对象,保存至沙箱,以便后续开发使用。
  103. NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  104. NSString *path = [docs[0]stringByAppendingPathComponent:@"json.plist"];
  105. [array writeToFile:path atomically:YES]; //把array里面的数据写入沙箱中的jspn.plist中。
  106. //给数据列表赋值
  107. NSMutableArray *arrayM = [NSMutableArray array];
  108. for (NSDictionary *dict in array) {
  109. Video *video = [[Video alloc]init];
  110. //给video赋值
  111. [video setValuesForKeysWithDictionary:dict];
  112. [arrayM addObject:video];
  113. }
  114. self.dataList = arrayM;
  115. //刷新表格
  116. [self.tableView reloadData];
  117. NSLog(@"%@", arrayM);  //这句话将调用video里面的description和nsarray+log里面的descriptionWithLocale
  118. }
  119. #pragma mark 加载json
  120. - (void)loadJson
  121. {
  122. NSLog(@"load json");
  123. //从web服务器加载数据
  124. NSString *str = @"http://www.baidu.com?format=json";  //这里是乱写的
  125. //提示:NSData本身具有同步方法,但是在实际开发中,不要使用次方法
  126. //在使用NSData的同步方法时,无法指定超时时间,如果服务器连接不正常,会影响用户体验。
  127. //NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
  128. //简历NSURL
  129. NSURL *url = [NSURL URLWithString:str];
  130. //建立NSURLRequest
  131. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
  132. //建立NSURLConnect的同步方法加载数据
  133. NSURLResponse *response = nil;
  134. NSError *error = nil;
  135. //同步加载数据
  136. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  137. //错误处理
  138. if (data != nil) {
  139. //下面这两句话本身没有什么意义,仅用于跟踪调试。
  140. NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  141. NSLog(@"%@", result);
  142. //在处理网络数据的时候,不要将NSData转换成nsstring。
  143. [self handlerJSONData:data];
  144. }else if (data == nil && error == nil){
  145. NSLog(@"空数据");
  146. }else
  147. {
  148. NSLog(@"%@", error.localizedDescription);
  149. }
  150. }
  151. #pragma mark 加载xml
  152. - (void)loadXML
  153. {
  154. NSLog(@"load xml");
  155. }
  156. //- (void)viewDidLoad
  157. //{
  158. //    [super viewDidLoad];
  159. //}
  160. @end

ios网络学习------6 json格式数据的请求处理的更多相关文章

  1. ios网络学习------8 xml格式数据的请求处理 用代码块封装

    #pragma mark 载入xml - (void)loadXML { //获取网络数据. NSLog(@"load xml"); //从webserver载入数据 NSStri ...

  2. iOS开发之JSON格式数据的生成与解析

    本文将从四个方面对IOS开发中JSON格式数据的生成与解析进行讲解: 一.JSON是什么? 二.我们为什么要用JSON格式的数据? 三.如何生成JSON格式的数据? 四.如何解析JSON格式的数据? ...

  3. ios网络学习------4 UIWebView的加载本地数据的三种方式

    ios网络学习------4 UIWebView的加载本地数据的三种方式 分类: IOS2014-06-27 12:56 959人阅读 评论(0) 收藏 举报 UIWebView是IOS内置的浏览器, ...

  4. 转载 -- iOS开发之JSON格式数据的生成与解析

    本文将从四个方面对IOS开发中JSON格式数据的生成与解析进行讲解: 一.JSON是什么? 二.我们为什么要用JSON格式的数据? 三.如何生成JSON格式的数据? 四.如何解析JSON格式的数据? ...

  5. Spring MVC 学习笔记11 —— 后端返回json格式数据

    Spring MVC 学习笔记11 -- 后端返回json格式数据 我们常常听说json数据,首先,什么是json数据,总结起来,有以下几点: 1. JSON的全称是"JavaScript ...

  6. JS学习笔记(3)--json格式数据的添加,删除及排序方法

    这篇文章主要介绍了json格式数据的添加,删除及排序方法,结合实例形式分析了针对一维数组与二维数组的json格式数据进行增加.删除与排序的实现技巧,需要的朋友可以参考下   本文实例讲述了json格式 ...

  7. 解析json格式数据

    实现目标 读取文件中的json格式数据,一行为一条json格式数据.进行解析封装成实体类. 通过google的Gson对象解析json格式数据 我现在解析的json格式数据为: {",&qu ...

  8. Android读取JSON格式数据

    Android读取JSON格式数据 1. 何为JSON? JSON,全称为JavaScript Object Notation,意为JavaScript对象表示法. JSON 是轻量级的文本数据交换格 ...

  9. 使用基于Android网络通信的OkHttp库实现Get和Post方式简单操作服务器JSON格式数据

     目录 前言 1 Get方式和Post方式接口说明 2 OkHttp库简单介绍及环境配置 3 具体实现 前言 本文具体实现思路和大部分代码参考自<第一行代码>第2版,作者:郭霖:但是文中讲 ...

随机推荐

  1. js计时器方法 setInterval(),setTimeout()

    window.setInterval() 周期性地调用一个函数(function)或者执行一段代码. var intervalID = window.setInterval(func, delay[, ...

  2. 精彩的javascript对象和数组混合相加

    最近遇到一个让人困解的一个问题:一个简单的js加法运算表达式: +[]; //这里加上一个空数组得到什么???答案:'1'; 为什么答案是1,一开始我也很困惑:后来我读了一篇文章才知道:在javasc ...

  3. 使用Netty收发二进制报文问题记

    1.java二进制编解码 byteBuffer.flip() byteBuffer.getInt() 与 byteBuf.getInt(11) 2.粘包拆包问题 LengthFieldBasedFra ...

  4. Unity中通过类名字符串取组件类型的方法(Types.GetType用法)

    正常调用Type.GetType取不到组件,因为会先创建实例在获取,而Unity组件无法通过new来创建. 第二种创建方式是通过程序集,具体如下 Assembly.GetExecutingAssemb ...

  5. C++ Programming language读书笔记

    C语言,结构化程序设计.自顶向下.逐步求精及模块化的程序设计方法;使用三种基本控制结构构造程序,任何程序都可由顺序.选择.循环三种基本控制结构构造. 模块结构:"独立功能,单出.入口&quo ...

  6. Oracle的多表查询

    多表查询概念: 所谓多表查询,又称表联合查询,即一条语句涉及到的表有多张,数据通过特定的连接进行联合显示. 基本语法: select column_name,.... from table1,tabl ...

  7. 《BI项目笔记》历年感官评吸质量均值变化分析Cube的建立

    分析主题主要维度:烟叶级别.烟叶级别按等级信息.烟叶级别按分级标准(标准维度)产地(父子维度)检测时间(时间维度,以Tqc_Raw_SmokingTest .CheckTime字段派生CheckDat ...

  8. GIS服务器需求分析

    一. 需求概要 1 边界 核心职责 接收并存储外部各方系统GPS数据 GPS数据实时分发, 轨迹检索   2 流程 GIS客户端向GIS服务器订购 GIS客户端向GIS服务器订购号码(仅有号码这一项业 ...

  9. 函数指针与指针函数以及typedef

    c难于理解的是指针,其魅力之处也是指针,函数方法结构,化繁为简可以理解为:返回值 函数名(形参表),具体来说: 返回值:1.可以为空void 2.基本数据类型char short int long f ...

  10. stage3D之疑问

    1.stage3D本身是建立在图形API(如DirectX.Opengl等)之上的一套API,那么在创建stage3D demo时,如何指定使用哪种图形API呢?