iOS开发——多线程篇——快速生成沙盒目录的路径,多图片下载的原理、SDWebImage框架的简单介绍

iOS开发——多线程篇——快速生成沙盒目录的路径,多图片下载的原理、SDWebImage框架的简单介绍

一、快速生成沙盒目录的路径


沙盒目录的各个文件夹功能

 - Documents

- 需要保存由"应用程序本身"产生的文件或者数据,例如:游戏进度、涂鸦软件的绘图

- 目录中的文件会被自动保存在 iCloud

- 注意:不要保存从网络上下载的文件,否则会无法上架!

 - Caches

- 保存临时文件,"后续需要使用",例如:缓存图片,离线数据(地图数据)

- 系统不会清理 cache 目录中的文件

- 就要求程序开发时,"必须提供 cache 目录的清理解决方案"

 - tmp

- 保存临时文件,"后续不需要使用"

- tmp 目录中的文件,系统会自动清理

- 重新启动手机,tmp 目录会被清空

- 系统磁盘空间不足时,系统也会自动清理

- Preferences

- 用户偏好,使用 NSUserDefault 直接读写!

- 如果要想数据及时写入磁盘,还需要调用一个同步方法

下面这个类主要是为了方便你快速拿到沙盒目录里文件夹的路径

给NSString写个分类

NSString+CHG.h

#import <Foundation/Foundation.h>

@interface NSString (CHG)

// 用于生成文件在caches目录中的路径
- (instancetype)cacheDir;
// 用于生成文件在document目录中的路径
- (instancetype)docDir;
// 用于生成文件在tmp目录中的路径
- (instancetype)tmpDir;

@end

NSString+CHG.m

#import "NSString+CHG.h"

@implementation NSString (CHG)

- (instancetype)cacheDir
{
    // 1.获取caches目录
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // 2.生成绝对路径
    return [path stringByAppendingPathComponent:[self lastPathComponent]];
}

- (instancetype)docDir
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return [path stringByAppendingPathComponent:[self lastPathComponent]];
}

- (instancetype)tmpDir
{
    NSString *path = NSTemporaryDirectory();
    return [path stringByAppendingPathComponent:[self lastPathComponent]];
}
@end

二、多图片下载


这是模仿SDWebImage内部的实现原理写的

大部分都有注释  很容易懂的

#import "ViewController.h"
#import "XMGApp.h"
#import "NSString+XMG.h"

@interface ViewController ()

@property (nonatomic, strong) NSArray *apps; /**< 应用程序信息 */


@property (nonatomic, strong) NSMutableDictionary *imageCaches; /**< 图片内存缓存 */
@property (nonatomic, strong) NSMutableDictionary *operations;  /**< 任务缓存 */


@end

@implementation ViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.tableView.rowHeight = 150;
}

#pragma mark - UITableViewDatasource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.获取cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"app"];
    
    // 2.设置数据
    XMGApp *app = self.apps[indexPath.row];
    
    cell.textLabel.text = app.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"下载:%@", app.download];
    cell.imageView.image = [UIImage imageNamed:@"abc"];
    
    // 设置图片
    /*
     存在的问题:
     1.在主线程中下载图片, 可能会阻塞主线程
     2.重复下载
     */
    // 1.先从内存缓存中获取, 如果没有才去下载
    UIImage *image = self.imageCaches[app.icon];
    if (image == nil) {
        
        // 2.再从磁盘缓存中获取, 如果没有才去下载
        NSString *filePath = [app.icon cacheDir];
        __block NSData *data = [NSData dataWithContentsOfFile:filePath];
        
        if (data == nil) {
            NSLog(@"下载图片");
            /*
             存在的问题:
             1.重复设置
             2.重复下载
             */
            NSOperationQueue *queue = [[NSOperationQueue alloc] init];
            
            // 3.判断当前图片是否有任务正在下载
            NSBlockOperation *op = self.operations[app.icon];
            if (op == nil) {
                // 没有对应的下载任务
                op = [NSBlockOperation blockOperationWithBlock:^{
                    // 开启子线程下载
                    // 内存缓存中没有值, 需要下载
                    NSURL *url = [NSURL URLWithString:app.icon];
                    data = [NSData dataWithContentsOfURL:url];
                    if (data == nil) {
                        // 如果下载失败, 应该将当前图片对应的下载任务从缓存中移除 
                        以便于下次可以再次尝试下载
                        [self.operations removeObjectForKey:app.icon];
                        return;
                    }

                    UIImage *image = [UIImage imageWithData:data];
                    // 将下载好的图片缓存到内存缓存中
                    self.imageCaches[app.icon] = image;
                    
                    // 将下载好的图片写入到磁盘
                    [data writeToFile:filePath atomically:YES];
                    
                    // 回到主线程更新UI
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        NSLog(@"更新UI");
    //                    cell.imageView.image = image;
                        
                        // 刷新指定的行
                        // 0 / 4
                        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        
                        // 从缓存中将当前图片对应的下载任务移除
                        [self.operations removeObjectForKey:app.icon];
                    }];
                }];
                
                
                // 先将下载任务保存到缓存中
                self.operations[app.icon] = op;
                
                // 将任务添加到队列中
                [queue addOperation:op];
            }
            
            
        }else
        {
            NSLog(@"使用磁盘缓存");
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            UIImage *image = [UIImage imageWithData:data];
            
            // 将下载好的图片缓存到内存缓存中
            self.imageCaches[app.icon] = image;
            
            // 更新UI
            cell.imageView.image = image;
        }
    }else
    {
        NSLog(@"使用内存缓存");
        // 更新UI
        cell.imageView.image = image;
    }
    
    
    // 3.返回cell
    return cell;
}

// 接收到内存警告
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    // 释放当前不需要使用内存
    self.imageCaches = nil;
    self.operations = nil;
    self.apps = nil;
}

#pragma mark - lazy
- (NSArray *)apps
{
    if (!_apps) {
        // 1.从plist中加载数组
        NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        
        // 2.定义数组保存转换好的模型
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:arr.count];
        
        // 3.遍历数组中所有的字典, 将字典转换为模型
        for (NSDictionary *dict in arr) {
            XMGApp *app = [XMGApp appWithDict:dict];
            [models addObject:app];
        }
        _apps = [models copy];
    }
    return _apps;
}


- (NSMutableDictionary *)imageCaches
{
    if (!_imageCaches) {
        _imageCaches = [NSMutableDictionary dictionary];
    }
    return _imageCaches;
}

- (NSMutableDictionary *)operations
{
    if (!_operations) {
        _operations = [NSMutableDictionary dictionary];
    }
    return _operations;
}

@end

模型

#import <Foundation/Foundation.h>

@interface XMGApp : NSObject

@property (nonatomic, copy) NSString *name; /**< 名称 */
@property (nonatomic, copy) NSString *icon; /**< 图标 */
@property (nonatomic, copy) NSString *download; /**< 下载次数 */

- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)appWithDict:(NSDictionary *)dict;
@end

三、SDWebImage简介


1、这里下简单介绍下SDWebImage

应用在这里的作用之一:会自动进行内存缓存磁盘缓存

     - SDWebImage的磁盘缓存, 是按照时间来处理的, 只要缓存数据超过了最大的缓存时间, 就会自动删除

     - SDWebImage默认的磁盘缓存时间是多久? 

        + 1周

     - SDWebImage接收到内存警告会如何处理

        + 只要接收到内存警告就会调用 clearMemory 清空内存缓存

     - SDWebImage即将要被终结如何处理

        + 会调用 cleanDisk 方法, 删除过期的文件

     - SDWebImage存储到什么为止

        + caches文件夹下面

        + 新建一个default文件夹用于缓存

     - SDWebImage是如何清空缓存 ?

        + clearMemory

        + 移除NSCache中保存的所有图片对象

     

     - SDWebImage是如何清除磁盘

        + cleanDisk : 清除过期的

            * 遍历缓存目录, 找到所有过期的文件, 并删除

            * 查看当maxCacheSize的值, 如果删除之后缓存的大小, 还大于maxCacheSize, 那么就会从时间较早的开始继续删除, 直到缓存大小小于maxCacheSize为止

        + clearDisk : 清除所有

            * 直接干掉缓存文件夹

            * 重新创建一个新的文件夹, 作为缓存文件

     

     - SDWebImage可以直接播放GIF图片

        + 加载GIF图片, 然后取出GIF图片中所有的帧, 并且计算动画时间

        + 根据取出的帧和动画时间生产一张新的可动画的图片

     

     - SDWebImage它可以判断图片的类型

        + 图片的十六进制数据, 的前8个字节都是一样的, 所以可以同判断十六进制来判断图片的类型

        + PNG

        + JPG

        + ...

2、基于上面的例子,用SDWebImage来实现就更加方便简洁了

#import "ViewController.h"
#import "XMGApp.h"
#import "NSString+XMG.h"
#import "UIImageView+WebCache.h"

@interface ViewController ()

@property (nonatomic, strong) NSArray *apps; /**< 应用程序信息 */

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.rowHeight = 150;

}

#pragma mark - UITableViewDatasource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.获取cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"app"];
    
    // 2.设置数据
    XMGApp *app = self.apps[indexPath.row];
    
    cell.textLabel.text = app.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"下载:%@", app.download];
  
    
    // 在老版本的SDWebImage中, 以下方法是没有sd_前缀的
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"abc"]];
  
    // 3.返回cell
    return cell;
}

#pragma mark - lazy
- (NSArray *)apps
{
    if (!_apps) {
        // 1.从plist中加载数组
        NSString *path = [[NSBundle mainBundle] pathForResource:@"apps.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        
        // 2.定义数组保存转换好的模型
        NSMutableArray *models = [NSMutableArray arrayWithCapacity:arr.count];
        
        // 3.遍历数组中所有的字典, 将字典转换为模型
        for (NSDictionary *dict in arr) {
            XMGApp *app = [XMGApp appWithDict:dict];
            [models addObject:app];
        }
        _apps = [models copy];
    }
    return _apps;
}

@end

单独下载一张图片

 
    // 直接下载一张图片
    /*
     第1个参数: 需要下载图片的URL
     第2个参数: 下载的配置信息(例如是否需要缓存等等)
     第3个参数: 下载过程中的回调
     第4个参数: 下载完成后的回调
     
     */
    NSURL *url = [NSURL URLWithString:@"http://ia.topit.me/a/f9/0a/1101078939e960af9ao.jpg"];
    [[SDWebImageManager sharedManager] downloadImageWithURL:url options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        // receivedSize : 已经接受到的数据大小
        // expectedSize : 需要下载的图片的总大小
        NSLog(@"正在下载 %zd %zd", receivedSize, expectedSize);
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        // image : 下载好的图片
        // error: 错误信息
        // cacheType: 缓存的类型
        // finished: 是否下载完成
        // imageURL: 被下载的图片的地址
        NSLog(@"下载成功 %@", image);
    }];