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];
}
//解析數(shù)據(jù)
-(void)parserData{
//1.準備url
NSURL *url = [NSURL URLWithString:ACTIVITYLIST_URL];
//2.準備request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.創(chuàng)建session
NSURLSession *session = [NSURLSession sharedSession];
//4.創(chuàng)建任務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];//數(shù)組初始化!!!!!!!!!!!!!!!!!
for (NSDictionary *dic1 in dic[@"events"]) {
NewsModel *newsModel = [NewsModel new];
[newsModel setValuesForKeysWithDictionary:dic1];
[self.dataArray addObject:newsModel];
}
//返回主線程刷新數(shù)據(jù)
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}];
//5.執(zhí)行
[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;
}
//觀察者發(fā)現(xiàn)觀察的屬性發(fā)生變化的時候觸發(fā)
/*
-(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,需要區(qū)別對待
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>
/*
圖片下載完之后代理對象執(zhí)行此方法,將解析好的圖片對象傳出去
@param image 下載完的圖片對象
*/
-(void)imageDownLoaderFinishLoadingImage:(nonnull UIImage *)image;
@end
/*
這是一個能夠傳遞image對象的block
@param image 解析完成的image對象
*/
typedef void(^ImageDownLoaderBlock) ( UIImage *__nonnull image);
@interface ImageDownLoader : NSObject
/**
*
*
* @param urlString 網(wǎng)址字符串
* @param delegate 能將圖片傳值出去的代理對象
*/
+(void)downLoadImageWithUrlString:(nonnull NSString *)urlString andDelegate:(nonnull id<ImageDownLoaderDelegate>)delegate;
/**
* 這是一個封裝的解析圖片的方法,使用Block將值傳遞出去
*
* @param urlString 網(wǎng)址字符串
* @param block 能夠傳遞image對象的回調(diào)函數(shù)
*/
+(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.創(chuàng)建下載任務
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:)]) {
//讓代理在主線程內(nèi)執(zhí)行圖片加載的方法,確保UI正常顯示
dispatch_async(dispatch_get_main_queue(),^{
[delegate imageDownLoaderFinishLoadingImage:image];
});
}
}];
//4.執(zhí)行任務
[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.創(chuàng)建下載任務
// 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];
// /*
// 此情況出現(xiàn)的提示
// 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.創(chuàng)建下載任務
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