iOS--tableView图片加载

TableView加载图片一共用了两种方法.法一是导入ImageDownLoader头文件,法二使用到了SDWebImage的第三方#

ViewController.m#

//
//  ViewController.m
// tableView图片加载
//

//

#import "ViewController.h"
#import "NewsTableViewCell.h"
#import "NewsModel.h"
#import "UIImageView+WebCache.h"



#define  ACTIVITYLIST_URL @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)NSMutableArray *dataArray;


@end

@implementation ViewController

NSString *identifier = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    
    _tableView.dataSource = self;
    
    _tableView.delegate = self;
//    //注册,用xib不能直接注册!!!!!!!!!
//    [self.tableView registerClass:[NewsTableViewCell class] forCellReuseIdentifier:identifier];
    
    //xib下注册
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:identifier];
    
    
    [self.view addSubview:_tableView];
    //
    [self parserData];
    
}

//解析数据
-(void)parserData{
    //1.准备url
    NSURL *url = [NSURL URLWithString:ACTIVITYLIST_URL];
    //2.准备request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.创建session
    NSURLSession *session = [NSURLSession sharedSession];
    //4.创建任务dataTask
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (data != nil) {
        
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
           
            self.dataArray = [NSMutableArray array];//数组初始化!!!!!!!!!!!!!!!!!
            for (NSDictionary *dic1 in dic[@"events"]) {
                
                NewsModel *newsModel = [NewsModel new];
                
                [newsModel setValuesForKeysWithDictionary:dic1];
                [self.dataArray addObject:newsModel];
                
            }
            //返回主线程刷新数据
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
            });
        }
    }];
    //5.执行
    [task resume];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 255;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    NewsModel *newsM = _dataArray[indexPath.row];
    
    cell.titleLabel.text = newsM.title;
    cell.nameLabel .text = newsM.name;
    
    //法一:
    /*
    if (newsM.loadImage ==nil && newsM.isLoading ==NO) {
        //给cell一个占位符
        cell.imageV.image = [UIImage imageNamed:@"11.jpg"];
        //加载图片
          [newsM loadingImage];
        //添加观察者
        [newsM addObserver:self forKeyPath:@"loadImage" options:NSKeyValueObservingOptionNew context:(__bridge void *)indexPath];
        
    } else if (newsM.loadImage ==nil){
        cell.imageV.image = [UIImage imageNamed:@"10"];
        
    } else {
        cell.imageV.image = newsM.loadImage;/////
    }
        
    */
    //法二:
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:newsM.image]placeholderImage:[UIImage imageNamed:@"11.jpg"]];
    
    
    
    
    return cell;
}


//观察者发现观察的属性发生变化的时候触发
/*
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //获取新值
    UIImage *img = (UIImage *)change[NSKeyValueChangeNewKey];
    //获取正在显示的cell
    NSArray *array = [self.tableView indexPathsForVisibleRows];
    //
    NSIndexPath *index = (__bridge NSIndexPath *) context;
    
    if ([array containsObject:index]) {
//        //获取对应的cell
//        NewsTableViewCell *cell = [self.tableView cellForRowAtIndexPath:index];
//       //赋值
//        cell.imageV.image =img;
        [self.tableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];//效果同上
//        [self.tableView reloadData];//有同上效果但耗资源,弃用
    }
    
    //移除观察者
    [object removeObserver:self forKeyPath:@"loadImage"];
    
    
    
}
*/


/**
 *  /////////////
 */
- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

NewsModel.h#

//
//  NewsModel.h
// tableView图片加载
//

//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>


@interface NewsModel : NSObject


@property(nonatomic, strong)NSString *name;

@property(nonatomic, strong)NSString *title;

@property(nonatomic ,strong)NSString *image;


@property(nonatomic, strong)UIImage *loadImage;


//判断是否正在加载
@property(nonatomic, assign)BOOL isLoading;

-(void)loadingImage;

@end

NewsModel.m#

//
//  NewsModel.m
//  tableView图片加载
//
//

#import "NewsModel.h"
#import "ImageDownLoader.h"
@implementation NewsModel

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    
//    [super setValue:value forUndefinedKey:key];
}


-(void)setValue:(id)value forKey:(NSString *)key{
    [super setValue:value forKey:key];
    //owner里面有name,需要区别对待
    if ([key isEqualToString:@"owner"]) {
        _name = value[@"name"];
    }
}



- (NSString *)description
{
    return [NSString stringWithFormat:@"%@", _title];
}


-(void)loadingImage{
    
    [ImageDownLoader downLoadImageWithUrlString:_image andBlock:^(UIImage * _Nonnull image) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.loadImage  = image;
            _isLoading = NO;
        });
        
    }];
    _isLoading = YES;
}


@end

ImageDownLoader.h#

//
//  ImageDownLoader.h
//  ImageDownLoader
//

//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>


@protocol ImageDownLoaderDelegate <NSObject>
/*
 图片下载完之后代理对象执行此方法,将解析好的图片对象传出去
 
 @param image 下载完的图片对象
 
 */

-(void)imageDownLoaderFinishLoadingImage:(nonnull UIImage *)image;


@end

/*
 这是一个能够传递image对象的block
 
 @param  image 解析完成的image对象
 
 */
typedef void(^ImageDownLoaderBlock) ( UIImage *__nonnull image);




@interface ImageDownLoader : NSObject

/**
*
*
*  @param urlString 网址字符串
*  @param delegate  能将图片传值出去的代理对象
*/

+(void)downLoadImageWithUrlString:(nonnull NSString *)urlString andDelegate:(nonnull id<ImageDownLoaderDelegate>)delegate;


/**
 *  这是一个封装的解析图片的方法,使用Block将值传递出去
 *
 *  @param urlString 网址字符串
 *  @param block     能够传递image对象的回调函数
 */

+(void)downLoadImageWithUrlString:(nonnull NSString *)urlString andBlock:(ImageDownLoaderBlock __nonnull)block;


@end

ImageDownLoader.m#

//
//  ImageDownLoader.m
//  ImageDownLoader
//

//

#import "ImageDownLoader.h"

@implementation ImageDownLoader



+(void)downLoadImageWithUrlString:(NSString *)urlString andDelegate:(nonnull id<ImageDownLoaderDelegate>)delegate{
    
//1.准备URL
    NSURL *url = [NSURL URLWithString:urlString];
//2.准备session对象
    NSURLSession *session = [NSURLSession sharedSession];
//3.创建下载任务
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //获取图片对象
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
        
        //
        if (nil != delegate && [delegate respondsToSelector:@selector(imageDownLoaderFinishLoadingImage:)]) {
            //让代理在主线程内执行图片加载的方法,确保UI正常显示
    dispatch_async(dispatch_get_main_queue(),^{
                [delegate imageDownLoaderFinishLoadingImage:image];

    });
        }
        
    }];
//4.执行任务
    
    [task resume];
}





+(void)downLoadImageWithUrlString:(nonnull NSString *)urlString andBlock:(ImageDownLoaderBlock __nonnull)block{
    
//    NSString *headerString = [urlString substringToIndex:4];
//    
//    if ([headerString isEqualToString:@"http"]) {
//        
//        //1.准备URL
//        NSURL *url = [NSURL URLWithString:urlString];
//        //2.准备session对象
//        NSURLSession *session = [NSURLSession sharedSession];
//        //3.创建下载任务
//        NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//            //获取图片对象
//            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
//            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //使用Block将值传递出去
//                block(image);
//            });
//            
//            
//        }];
//        //4.重新开始任务
//        [task resume];
//
//    } else{
//        
//        @throw [NSException exceptionWithName:@"ImageDownLoader Error" reason:@"Your urlString maybe an illegal string" userInfo:nil];
//        /*
//         此情况出现的提示
//        2015-12-15 11:38:55.724 ImageDownLoader[2944:118088] *** Terminating app due to uncaught exception 'ImageDownLoader Error', reason: 'Your urlString maybe an illegal string'
//        */
//    }
    
//    
    //1.准备URL
    NSURL *url = [NSURL URLWithString:urlString];
    //2.准备session对象
    NSURLSession *session = [NSURLSession sharedSession];
    //3.创建下载任务
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //获取图片对象
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //使用Block将值传递出去
            block(image);
        });
    
    
    }];
    //4.重新开始任务
    [task resume];
    
}
@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容