In the method transmitData, the NSArray files is coming up nil. Where is the problem in my code? I save a file (we hit [file writeToURL: fileURL atomically: YES]) and then we call transmitData, but cannot retrieve the files.
#import "FileManagerService.h"
#import "SynthesizeSingleton.h"
@implementation FileManagerService
SYNTHESIZE_SINGLETON_FOR_CLASS(FileManagerService);
#define SAVEVOTER @"SV"
#define SAVESCRIPT @"SS"
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
-(void)saveFile:(NSData*)file:(NSString*)dataType
{
NSFileManager *manager = [NSFileManager defaultManager];
NSURL *fileURL;
NSString *fileName;
if (dataType == DATA_SAVE_VOTER)
{
fileName = [NSString stringWithFormat:@"%@01",SAVEVOTER];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
int fID = 0;
while ([manager fileExistsAtPath:[fileURL absoluteString]])
{
fID++;
fileName = [NSString stringWithFormat:@"%@%d",SAVEVOTER,fID];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
}
}
else if (dataType == DATA_SAVE_SCRIPT)
{
fileName = [NSString stringWithFormat:@"%@01",SAVESCRIPT];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
int fID = 0;
while ([manager fileExistsAtPath:[fileURL absoluteString]])
{
fID++;
fileName = [NSString stringWithFormat:@"%@%d",SAVESCRIPT,fID];
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
}
}
[file writeToURL:fileURL atomically:YES];
}
-(void)transmitData
{
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[self applicationDocumentsDirectory]absoluteString] error:NULL];
if (files == nil || [files count] <= 0)
{
NSLog(@"No files to transmit");
return;
}
for (id file in files)
{
NSData * dt = file;
NSString *str = [[NSString alloc]initWithData:dt encoding:NSUTF8StringEncoding];
NSLog(@"DataContents: %@",str);
}
}
@end
EDIT:
Upon more testing :
fileName = @"testfile";
fileURL = [[self applicationDocumentsDirectory]URLByAppendingPathComponent:fileName];
NSLog(@"URL1: %@",[fileURL absoluteString]);
My log is coming up Null. So I cant retrieve files because I am obviously saving with a null file location….why is this happening?
FIXED:
So I have no idea why, but [file writeToURL:fileURL atomically:YES] does NOT work and [[NSFileManager defaultManager] createFileAtPath:fileURL
contents:file
attributes:nil];
does work.
Use
and