我有兩種方法,首先檢查我是否已經下載了圖像,如果沒有從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]);
}
圖像已經成功下載並緩存到我的文檔目錄(我知道,因爲我可以在文件系統中看到它)。當我第一次調用這個方法時,它成功地重新加載了圖像,但是一旦我轉到另一個視圖,並且在我回到相同視圖時重新調用此方法,則它是空白的。但是,該URL是正確的。這裏有什麼問題?
我已經試過了,以及(在返回的地方作爲NSData的再初始化它),同樣的事情發生的。 – ManOx
你跟蹤過'filePath'和'pngPath'變量嗎? – Andrey
是的,文件路徑是正確的,並且pngPath是正確的。 – ManOx