2012-03-03 104 views
6

我有這樣的代碼,它應該工作完美,但我不能udnerstand爲什麼它不是:「操作無法完成(可可錯誤512)。」

+(NSString *)writeImageToFile:(UIImage *)image { 

    NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f); 


    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Images/"]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    BOOL isDirectory = NO; 
    BOOL directoryExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory]; 
    if (directoryExists) { 
     NSLog(@"isDirectory: %d", isDirectory); 
    } else { 
     NSError *error = nil; 
     BOOL success = [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error]; 
     if (!success) { 
      NSLog(@"Failed to create directory with error: %@", [error description]); 
     } 
    } 

    NSString *name = [NSString stringWithFormat:@"%@.jpg", [JEntry generateUuidString]]; 
    NSString *filePath = [path stringByAppendingPathComponent:name]; 
    NSError *error = nil; 
    BOOL success = [fullImageData writeToFile:filePath options:NSDataWritingAtomic error:&error]; 
    if (!success) { 
     NSLog(@"Failed to write to file with error: %@", [error description]); 
    } 

    return filePath; 
} 

它通過directoryExists沒有錯誤,但是當它到達將writeToFile,它給了我這個錯誤:

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x5634ee0 {NSFilePath=/var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/18DAE0BD-6CB4-4244-8ED1-9031393F6DAC.jpg, NSUnderlyingError=0x5625010 "The operation couldn’t be completed. Not a directory"} 

任何想法,這可能是爲什麼?

回答

8

當我在路徑@"Documents/Images/"中首先寫入文件時,我能夠重現您的錯誤,然後嘗試使用您的代碼編寫圖像。

我認爲有兩種可能的情景是:

1)您創建的錯誤該文件在您的應用程序的以前的執行。如果您使用菜單重置模擬器,這將得到解決:iOS模擬器>重置內容和設置,並從設備上卸載應用程序:長按>點擊x符號

2)在您的應用程序中有一些代碼創建此文件。如果是這種情況,您應該找到該代碼並將其刪除。

+0

看來第一個解決方案是正確的。感謝那。 :) – Andrew 2012-03-03 17:43:35

+0

@sch:我知道那天晚些時候,但是非常感謝你。我的問題是我的代碼在iPad上運行良好,但不在模擬器上運行。重置內容和設置解決了這個問題。 – Robert 2012-11-27 16:22:54

+1

我有問題2)。但首先,編譯器說沒有持久存儲。現在我嘗試添加一個持久性存儲,因爲我已經擁有可可錯誤512而失敗!好! – coolcool1994 2013-07-02 14:27:47

3

FoundationErrors.h

NSFileWriteUnknownError = 512 

嘗試使用withIntermediateDirectories:YES

1

在我的情況一段時間'。'在目錄名稱中(例如〜/ Documents/someDir.dir/somefile)是導致問題的原因。我刪除了違規角色,錯誤消失了。

相關問題