我有两种方法,首先检查我是否已经下载了图像,如果没有从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是正确的。这有什么不对?
答案 0 :(得分:0)
也许,你应该这样做:
image = [UIImage imageWithContentsOfFile: nameOfFile];
答案 1 :(得分:0)
1)你不应该像你那样写入硬编码路径(即“Documents / xxx”),而是要求提供Application Support目录,使用它,并标记文件以便它们不会上传到iCloud(除非你想要那个)。见this link on the specifics。在其中创建一个子文件夹,并将其标记为不支持iCloud备份。
2)尝试更改:
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];
到
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]]];