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 ()

@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 *)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 
#import 


@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 
#import 


@protocol ImageDownLoaderDelegate 
/*
 图片下载完之后代理对象执行此方法,将解析好的图片对象传出去
 
 @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)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)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

你可能感兴趣的:(iOS--tableView图片加载)