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];
    
}

//解析數(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

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內(nèi)容