缓存来自 URL 的图像工作,但返回空白图像



我有两种方法,首先检查我是否已经下载了图像,如果没有,则从URL检索图像并将其缓存到我的应用程序中的文档目录中。如果是,它只是检索它,如果我有互联网连接,将重新下载它。以下是两种方法:

- (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]);
}

该图像已成功下载并缓存到我的文档目录(我知道,因为我可以在文件系统中看到它)。当我第一次调用此方法时,它成功地重新加载了图像,但是一旦我转到另一个视图,并在我返回到同一视图时重新调用此方法,它就是空白的。然而,网址是正确的。这是怎么回事?

1)您不应该像现在这样写入硬编码路径(即"Documents/xxx"),而是询问应用程序支持目录,使用它,并标记文件,以便它们不会上传到iCloud(除非您需要)。有关具体信息,请参阅此链接。在其中创建一个子文件夹,并将其标记为不适用于iCloud备份。

2) 尝试更改:

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

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

也许,你应该这样做:

image = [UIImage imageWithContentsOfFile: nameOfFile];

最新更新