UIImageView图片加载的几种方式

作者: 见哥哥长高了 | 来源:发表于2016-03-01 22:04 被阅读1709次

    UIImageView图片加载很常用...所以我们需要每个人都熟练掌握网络图片加载的方式和用法.....其实我说这些都是废话,但是** 大碗 **入场之前一般都有一段开场,小编在此装一下逼不过分....希望大家理解,,
    废话不多说,,,,大家往下看

    1、NSURLSessionDataTask
    - (IBAction)dataTask:(UIButton *)sender {
        //1 准备url
        NSURL *url =[NSURL URLWithString:IMG_URL];
        //2 准备Session
        NSURLSession *session = [NSURLSession sharedSession];
        //3 准备会话
        NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            UIImage *image = [UIImage imageWithData:data];
            //在主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                self.aImageView.image = image;
            });
        }];
        [task resume];//执行
    }
    
    2、NSURLSessionDownloadTask
    - (IBAction)downLoad:(UIButton *)sender {
        //准备URL
        NSURL *url = [NSURL URLWithString:IMG_URL];
        //准备Session
        NSURLSession *session =[NSURLSession sharedSession];
        //创建会话
        NSURLSessionDownloadTask *downLoadTask =[session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //打印临时文件
            NSLog(@"临时文件:%@",location);
            
            //根据下载存放到的本地路径的文件来创建data对象
            NSData *tempData = [NSData dataWithContentsOfURL:location];
            UIImage *image =[UIImage imageWithData:tempData];
            //刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                self.aImageView.image = image;
            });
        }];
        //启动任务
        [downLoadTask resume];
        //打印临时文件夹
        NSString *temp = NSTemporaryDirectory();
        NSLog(@"%@",temp);
    }
    
    

    小伙伴们看了以上内容此时你是什么心情呢? 不要激动~~~~~~精彩的还在后面呢!下面见哥赠送一份 由于本人从小学开始就死了语文老师,,,如有错误 还请谅解 咱们继续。

    3、封装Delegate 方法对UIImageView图片加载
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    @protocol ImageDownLoadDelegate <NSObject>
    //图片加载完成之后代理对象执行此方法 将解析好的图片传出去
    //@param image 下载完的图片对象
    -(void)imageDownLoadFanishLoadingImage:(nonnull UIImage *)image;
    @end
    
    @interface ImageDownLoad : NSObject
    //这是一个封装下载图片的方法 urlString 网址字符串 delegate 将图片传送出去的对象
    +(void)downLoadImageWithURLString:(nonnull NSString *)urlString delegate:(nonnull id<ImageDownLoadDelegate>)delegate;
    @end
    

    .m中实现+(void)downLoadImageWithURLString:(nonnull NSString *)urlString delegate:(nonnull id<ImageDownLoadDelegate>)delegate;方法

    #import "ImageDownLoad.h"
    
    @implementation ImageDownLoad
    +(void)downLoadImageWithURLString:(nonnull NSString *)urlString delegate:(nonnull id<ImageDownLoadDelegate>)delegate{
        //准备URL
        NSURL *url =[NSURL URLWithString:urlString];
        //准备Session对象
        NSURLSession *session =[NSURLSession sharedSession];
        //创建下载对象
        NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //获取图片对象
            UIImage *image =[UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
            if (delegate != nil && [delegate respondsToSelector:@selector(imageDownLoadFanishLoadingImage:)]) {
                //让代理在主线程内执行图片的方法 确保UI正常显示
                dispatch_async(dispatch_get_main_queue(), ^{
                [delegate imageDownLoadFanishLoadingImage:image];
            });
            }
        }];
        //执行任务
        [downLoadTask resume];
    }
    

    ViewController.m中进行调用

    - (IBAction)delegate:(UIButton *)sender {
        NSLog(@"delegate");
        [ImageDownLoad downLoadImageWithURLString:IMG_URL delegate:self];  //类调用
    }
    

    实现协议里面的方法-----

    -(void)imageDownLoadFanishLoadingImage:(UIImage *)image{
        self.aImageView.image = image;
    }
    

    见哥是一个肤浅的人,,,, 嘿嘿 ....所以写出来的东西都是都很容易接受,,,,这还是局废话 咱们继续

    3、封装Block 方法对UIImageView图片加载
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    //这是一个能够传递image对象的Block image是解析完成的image对象 用于回调
    typedef void(^ImageDownLoadBlock)(UIImage *__nonnull image);
    
    @interface ImageDownLoad : NSObject
    //这是一个封装的解析图片的方法 使用Block经值传出去 能够传递image对象的回调函数urlString网址字符串
    +(void)downLoadImageWithURLString:(nonnull NSString *)urlString andBlock:(ImageDownLoadBlock __nonnull)block;
    @end
    

    .m实现部分

    +(void)downLoadImageWithURLString:(nonnull NSString *)urlString andBlock:(ImageDownLoadBlock __nonnull)block{
        
        NSString *hesderString = [urlString substringToIndex:4];
        if ([hesderString isEqualToString:@"http"]) {
            NSURLSession *session =[NSURLSession sharedSession];
            NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:urlString] 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);
                });
            }];
            [task resume];
        }else{
            //抛出异常
            @throw [NSException exceptionWithName:@"ImageDownLoad Error" reason:@"Your urlString mayBe an Illegal string" userInfo:nil];
        }
    }
    

    ViewVontroller.m调用

    - (IBAction)block:(UIButton *)sender {
        NSLog(@"block");
        [ImageDownLoad downLoadImageWithURLString:IMG_URL andBlock:^(UIImage * _Nonnull image) {
            self.aImageView.image = image;
        }];
    }
    

    下面介绍完最后一种方法之后,睡觉 ,昨天失眠 做梦梦见自己结婚 激动之下醒了 然后就没有结果了。。。。。

    5、SDWebImage 第三方

    导入头文件import "UIImageView+WebCache.h" 一行代码搞定 一下是其中几种方法 供参考

        [cell.imageView sd_setImageWithURL:<#(NSURL *)#> placeholderImage:<#(UIImage *)#>]
        [cell.imageView sd_setImageWithURL:<#(NSURL *)#> placeholderImage:<#(UIImage *)#> completed:<#^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)completedBlock#>]
        [cell.imageView sd_setImageWithURL:<#(NSURL *)#> placeholderImage:<#(UIImage *)#> options:<#(SDWebImageOptions)#>]
        [cell.imageView sd_setImageWithURL:<#(NSURL *)#> placeholderImage:<#(UIImage *)#> options:<#(SDWebImageOptions)#> completed:<#^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)completedBlock#>]
        [cell.imageView sd_setImageWithURL:<#(NSURL *)#> placeholderImage:<#(UIImage *)#> options:<#(SDWebImageOptions)#> progress:<#^(NSInteger receivedSize, NSInteger expectedSize)progressBlock#> completed:<#^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)completedBlock#>]
    

    相关文章

      网友评论

      本文标题:UIImageView图片加载的几种方式

      本文链接:https://www.haomeiwen.com/subject/dqcnkttx.html