I have an app running in the XCode simulator (v6.4); this is the pertinent code:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// read the file back into databuffer...
NSFileHandle *readFile = [NSFileHandle fileHandleForReadingAtPath:[documentsPath stringByAppendingPathComponent: @"Backup.txt"]];
NSData *databuffer = [readFile readDataToEndOfFile];
[readFile closeFile];
// compress the file
NSData *compressedData = [databuffer gzippedData] ;
// Write to disk
NSString *outputPath = [NSString stringWithFormat:@"%@/%@%@.zip", documentsPath, venueName, strDate];
_BackupFilename = fileName; // save for upload
NSFileHandle *outputFile = [NSFileHandle fileHandleForWritingAtPath:outputPath];
NSError *error = nil;
// write the data for the backup file
BOOL success = [compressedData writeToFile: outputPath options: NSDataWritingAtomic error: &error];
if (error == nil && success == YES) {
NSLog(@"Success at: %@",outputPath);
}
else {
NSLog(@"Failed to store. Error: %@",error);
}
[outputFile closeFile];
I'm trying to create a backup of a file by taking the file, compressing it and then writing it out. I get an error Failed to store. Error: (null)); why is it failing without returning the error code?
There are quite a few things wrong here. To start. change your if
statement to:
if (success) {
Never explicitly compare a BOOL
value to YES
or NO
.
You also never use outputFile
so remove that code. It may interfere with the call to writeToFile:
.
And there's no point in using the file handle to read the data. Just use NSData dataWithContentsOfFile:
.
And don't build paths using stringWithFormat:
.
Overall, I would write your code as:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// read the file back into databuffer...
NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"Backup.txt"]];
NSData *databuffer = [NSData dataWithContentsOfFile:dataPath];
// compress the file
NSData *compressedData = [databuffer gzippedData];
// Write to disk
NSString *outputName = [NSString stringWithFormat:@"%@%@.zip", venueName, strDate];
NSString *outputPath = [documentsPath stringByAppendingPathComponent:outputName];
// write the data for the backup file
NSError *error = nil;
BOOL success = [compressedData writeToFile:outputPath options:NSDataWritingAtomic error:&error];
if (success) {
NSLog(@"Success at: %@",outputPath);
} else {
NSLog(@"Failed to store. Error: %@",error);
}
Since success
is still NO
and error
is still nil
, then most likely this means that compressedData
is nil
. This probably means that databuffer
is nil
which means that there is no file named Backup.txt
(case matters) in the Documents
folder.