iOS本地图片缓存无法加载解决办法

最近做了一个功能,把图片缓存到App中。保存成功后,通过地址加载图片,发现可以成功。

但是关闭程序后,再次启动,发现直接通过保存的地址加载图片总是失败。

解决方法:获取图片时,需要重新拼接图片路径,就可以加载成功了。

 

保存图片代码:

+ (NSString *)saveImage:(UIImage *)image imageName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
    
    BOOL success;
    
    NSError *error;
    
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *imgCachePath = @"img-cache";
    
    NSString *imgCacheAbsolutePath = [NSString stringWithFormat:@"%@/html-resources/%@",documentsDirectory,imgCachePath];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //判断是否存在改文件夹,不存在创建
    success = [fileManager fileExistsAtPath:imgCacheAbsolutePath];
    
    if(!success) {
        
        [fileManager createDirectoryAtPath:imgCacheAbsolutePath withIntermediateDirectories:YES attributes:nil error:&error];
        
    }
    
    // 图片名
    NSString *imgPath = [NSString stringWithFormat:@"%@/%@.jpg",imgCachePath,imageName];
    NSString *imgAbsolutePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/html-resources/%@", imgPath]];
    [imageData writeToFile:imgAbsolutePath atomically:YES];
    return imageName;
}

 

加载图片代码

- (UIImage *)getSaveImage:(NSString *)imageName
{
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
       
    NSString *imgCachePath = @"img-cache";
       
    NSString *imgPath = [NSString stringWithFormat:@"%@/%@.jpg",imgCachePath,imageName];
    NSString *imgAbsolutePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/html-resources/%@", imgPath]];
    
    return [UIImage imageWithContentsOfFile:imgAbsolutePath];
}

 

你可能感兴趣的:(iOS开发学习,iOS)