2013-05-19 58 views
2

我試圖使用以下方法加載圖像。iOS可以從磁盤寫入或讀取圖像數據

我首先檢查我是否已經有磁盤上的圖像,如果我這樣做,我只會從磁盤獲取圖像數據並加載它,否則我會從服務器獲取圖像並寫入磁盤,以便第二次,我需要的圖像,我不會訪問服務器。

問題是它似乎沒有寫入或從磁盤讀取。每次我想要第二次加載圖像時,它仍然會從服務器讀取它們,並且不會調用這些圖像。

如果有人有任何想法,我不知道我做錯了什麼?

-(UIImage *)imageWith:(NSString *)imageName isPreview:(BOOL)preview 
{ 
    //imageName is something like "56.jpg" 

    NSString *mainOrPreview = @"Preview"; 
    if (!preview) { 
     mainOrPreview = @"Main"; 
    } 

    NSString *pathSuffix = [[@"Images" stringByAppendingPathComponent:mainOrPreview] stringByAppendingPathComponent:imageName]; 
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:pathSuffix]; 
    NSData *imageData = [NSData dataWithContentsOfFile:path]; 

    if (imageData) { 
     NSLog(@"disk"); 
    } 

    if (!imageData && [self connected]) { 

      imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[serverURL stringByAppendingPathComponent: pathSuffix]]]; 

     if (imageData) { 

      [imageData writeToFile:path atomically:YES]; 
     } 

     NSLog(@"server"); 
    } 

     return [UIImage imageWithData:imageData]; 
} 

回答

3

問題是目錄不存在超越Documents。因此,寫入文件的嘗試失敗。使用具有NSError參數的文件方法總是一個好主意,因此您可以檢查結果。

您只需更新實際從服務器寫入圖像的代碼。

if (!imageData && [self connected]) { 
    // This needs to be done in on a background thread! 
    imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[serverURL stringByAppendingPathComponent: pathSuffix]]]; 

    if (imageData) { 
     [[NSFileManager defaultManager] createDirectoryAtPath:[path stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; 
     [imageData writeToFile:path atomically:YES]; 
    } 

    NSLog(@"server"); 
} 
+0

OMG!你是個天才!你剛剛救了我。非常感謝你。 – Mona

相關問題