我有两种方法,首先检查我是否已经下载了图像,如果没有,则从 URL 检索图像并将其缓存到我的应用程序中的 docs 目录中。如果是,它只是检索它,如果我有互联网连接,将重新下载它。以下是两种方法:
- (UIImage *) getImageFromUserIMagesFolderInDocsWithName:(NSString *)nameOfFile
{
UIImage *image = [UIImage imageNamed:nameOfFile];
if (!image) // image doesn't exist in bundle...
{
// Get Image
NSString *cleanNameOfFile = [[[nameOfFile stringByReplacingOccurrencesOfString:@"." withString:@""]
stringByReplacingOccurrencesOfString:@":" withString:@""]
stringByReplacingOccurrencesOfString:@"/" withString:@""];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@.png", cleanNameOfFile]];
image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];
if (!image)
{
// image isn't cached
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];
[self saveImageToUserImagesFolderInDocsWithName:cleanNameOfFile andImage:image];
}
else
{
// if we have a internet connection, update the cached image
/*if (isConnectedToInternet) {
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];
[self saveImageToUserImagesFolderInDocsWithName:cleanNameOfFile andImage:image];
}*/
// otherwise just return it
}
}
return image;
}
这是保存图像
- (void) saveImageToUserImagesFolderInDocsWithName:(NSString *)nameOfFile andImage:(UIImage *)image
{
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@.png", nameOfFile]];
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
NSLog(@"directory: %@", [[UIImage alloc] initWithContentsOfFile:pngPath]);
}
该图像已成功下载并缓存到我的文档目录(我知道是因为我可以在文件系统中看到它)。我第一次调用这个方法时它成功地重新加载了图像,但是一旦我转到另一个视图,当我回到同一个视图时重新调用这个方法,它就是空白的。但是,URL 是正确的。这里有什么问题?