Friday, April 27, 2012

Error saving data to cache directory (iPhone)


I am trying to save images using the following code:




- (void)writeData{

if(cacheFileName==nil)
return;
if(cacheDirectoryPath==nil)
return;


if (![[NSFileManager defaultManager] fileExistsAtPath:[self filePath]]) {

NSData *imageData = UIImageJPEGRepresentation(self.image, 0.9);

NSError *writeError= nil;

BOOL didWrite = [imageData writeToFile:[self filePath] options:NSAtomicWrite error:&writeError];

if(writeError)
NSLog([writeError localizedDescription]);

if(didWrite)
NSLog(@"image saved");
else
NSLog(@"image not saved");


}
}





- (NSString *)filePath{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
NSString *filename = [cacheDirectory stringByAppendingPathComponent:cacheDirectoryPath];
filename = [filename stringByAppendingPathComponent:cacheFileName];
NSLog(filename);

return filename;

}



I get an error:




2009-06-23 16:39:19.740 XXX[33454:20b] Operation could not be completed. (Cocoa error 4.)



I looked this up and see the error has the following meaning:




NSFileNoSuchFileError = 4, // Attempt to do a file system operation on a non-existent file



Which doesn't make sense since the file shouldn't exist.



I have tried writing the png representation and using the convenience method:




- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag



I am using similar code to save plists, and they work fine. I am not sure what the problem is. Any ideas?


Source: Tips4all

1 comment:

  1. I see that you use some intermediate directory within the Cache Directory, are it/they created? If not try removing them or use

    NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:


    to create them before

    ReplyDelete