2012-09-29 88 views
0

我有兩種方法,首先檢查我是否已經下載了圖像,如果沒有從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是正確的。這裏有什麼問題?

回答

0

1)你不應該寫入一個硬編碼路徑爲你做(即「文檔/ XXX」),而是要求應用程序支持目錄,使用它,也標記文件,以便他們不會上傳到iCloud(除非你想)。見this link on the specifics。在其中創建一個子文件夾並將其標記爲不用於iCloud備份。

2)嘗試改變:

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

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

也許,你應該做的:

image = [UIImage imageWithContentsOfFile: nameOfFile]; 
+0

我已經試過了,以及(在返回的地方作爲NSData的再初始化它),同樣的事情發生的。 – ManOx

+0

你跟蹤過'filePath'和'pngPath'變量嗎? – Andrey

+0

是的,文件路徑是正確的,並且pngPath是正確的。 – ManOx