IOS- 网络图片缓存到沙盒中 ,离线取出。

时间:2023-03-09 22:51:14

一、缓存图片

//1.首先创建在沙盒中创建一个文件夹用于保存图片

NSFileManager *fileManager = [[NSFileManager alloc] init];

NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *createPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];

// 判断文件夹是否存在,如果不存在,则创建

if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {

[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];

} else {

NSLog(@"FileDir is exists.");

}

for (int i = 0; i < viewsArray.count; i++) {

UIImageView * imageV = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth * i, 0, screenWidth, self.homePageview.height)];

[imageV sd_setImageWithURL:[viewsArray objectAtIndex:i]placeholderImage:[UIImage imageNamed:@"Moren6p.png"]];

UITapGestureRecognizer * tap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];

[imageV addGestureRecognizer:tap];

imageV.userInteractionEnabled = YES;

[self.homePageview addSubview:imageV];

UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[viewsArray objectAtIndex:i]]];

//2.缓存我所需要的图片

NSString *path_sandox = NSHomeDirectory();

//创建路径

NSString *CachePath = [NSString stringWithFormat:@"/Documents/Image/HomeScroll%d.png",i];

//设置一个图片的存储路径

NSString *imagePath = [path_sandox stringByAppendingString:CachePath];

//把图片直接保存到指定的路径(同时应该把图片的路径imagePath存起来,下次就可以直接用来取)

[UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];

}

二、读取图片

//1.首先获取沙盒路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *fileManage = [NSFileManager defaultManager];

NSString *CacheDocuments = [documentsDirectory stringByAppendingPathComponent:@"/Image”];//我把图片缓存到沙盒中的Document下得Image文件夹中

NSArray *CacheScrollImage = [fileManage subpathsOfDirectoryAtPath:CacheDocuments error:nil];//这个是获取Image文件夹下所有文件的文件名数组

//2.离线加载沙盒中缓存的图片

for (int i =0; i<CacheScrollImage.count; i++) {

NSString * CacheImage = [NSString stringWithFormat:@"Image/HomeScroll%d.png",i];

NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:CacheImage];

NSData *data = [fileManage contentsAtPath:myDirectory];

UIImage * image = [UIImage imageWithData:data];

}