最近做了一個功能,把圖片緩存到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];
}