0

我有两种方法,首先检查我是否已经下载了图像,如果没有,则从 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 是正确的。这里有什么问题?

4

2 回答 2

0

也许,你应该这样做:

image = [UIImage imageWithContentsOfFile: nameOfFile];
于 2012-09-29T17:23:34.097 回答
0

(除非你想要那个)。有关详细信息,请参阅此链接。在其中创建一个子文件夹并将其标记为不用于 iCloud 备份。

2)尝试改变:

image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];

image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]]];
于 2012-09-29T21:24:12.470 回答