iOS-->下载图片解析JSON数据实例

xcode.png

请求数据,设置到tableView上的实例

本次小Demo的完成的主要操作是:根据URL向服务器请求数据,解析服务器返回的JSON数据,并将这些数据封装成模型设置到tableView上面。具体代码如下:

#import "ViewController.h"
#import "MJExtension.h"
#import "UIImageView+WebCache.h"
#import "WJCellItem.h"
#import <MediaPlayer/MediaPlayer.h>
#import "WJTableViewCell.h"
@interface ViewController ()
@property (strong,nonatomic)NSArray *dataArr;
@end

@implementation ViewController
-(NSArray *)dataArr{
    if (_dataArr==nil) {
        _dataArr=[NSArray array];
    }
    return _dataArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //获取请求路径
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *session=[NSURLSession sharedSession];
    //根据会话对象创建请求任务
    NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析从服务器返回的JSON数据
       NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        //拿到videos对应的数组,里面装着多个字典,要想到把这个字典数组转换成模型数组
        NSArray *array=dict[@"videos"];
        //改变模型属性的属性值
      [WJCellItem mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{@"ID":@"id"};
        }];
        //将数组中的字典数据都转换成模型
        self.dataArr=[WJCellItem mj_objectArrayWithKeyValuesArray:array];
        //由于NSURLSession处理任务的操作默认都是在子线程中进行的,而像刷新数据设置图片这种操作必须在主线程中进行,因此必须进行线程间的通信,转到主队列,执行UI操作
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.tableView reloadData];
        }];

    }];
    //发送请求
    [dataTask resume];

    }
//一共有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
//每一个cell的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   static NSString *ID=@"cell";
    //cell的重用机制
    WJTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell=[[WJTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    //根据行号来提取模型,并设置数据
    WJCellItem *item=self.dataArr[indexPath.row];
    cell.textLabel.text=item.name;
    cell.detailTextLabel.text=[NSString stringWithFormat:@"播放数量为:%@",item.length];
    //拼接路径
    NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.image];
    //利用框架来下载并设置图片
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"xcode"]];
    return cell;
}
//当点击cell时回来到这个方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //拿到模型
    WJCellItem *item=self.dataArr[indexPath.row];
    //拼接路径
    NSString *path=[@"http://120.25.226.186:32812/"stringByAppendingString:item.url];
    NSURL *url=[NSURL URLWithString:path];
    //创建一个能播放视频的控制器实例
    MPMoviePlayerViewController *vc=[[MPMoviePlayerViewController alloc]initWithContentURL:url];
    [self presentViewController:vc animated:YES completion:nil];
}

@end

模型类:

#import <Foundation/Foundation.h>

@interface WJCellItem : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *length;
@property (nonatomic, strong) NSString *image;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) NSString *ID;
@end

由于占位图片与下载的图片的真实尺寸存在差别,当这种差别比较大的时候我们就需要自定义cell来固定个字控件的大小:

#import "WJTableViewCell.h"
#import "UIView+Frame.h"
@implementation WJTableViewCell

-(void)layoutSubviews{
    [super layoutSubviews];
    self.imageView.x=5;
    self.imageView.y=5;
    self.imageView.width=100;
    self.imageView.heigth=self.heigth;
    self.textLabel.x=CGRectGetMaxX(self.imageView.frame)+5;
    self.detailTextLabel.x=CGRectGetMaxX(self.imageView.frame)+5;
}
@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • //我所经历的大数据平台发展史(三):互联网时代 • 上篇http://www.infoq.com/cn/arti...
    葡萄喃喃呓语阅读 51,343评论 10 200
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 可爱的胖娃娃,肉乎乎,胖嘟嘟,惹人爱 怎么表现才能越看越爱呢? 第一,头要占到身长的三分之一或四分之一,俗称大头娃...
    圆零阅读 487评论 0 0
  • 20170118 "我的简历"里面的“职业理想” 与 “我的”界面中的“求职意向” 不一样。  擦。 我要改 ...
    plantAtree_dAp阅读 274评论 0 0