ios网络学习------6 json格式数据的请求处理

 

ios网络学习------6 json格式数据的请求处理

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