davidOhara davidOhara - 1 month ago 9
Objective-C Question

File from Documents into NSData

i want to grab a file from the Documents Directory into a

NSData
Object, but if i do so my
NSData
is always
NIL
:

filepath = [[NSString alloc] init];
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:fileNameUpload];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];

-(NSString *)GetDocumentDirectory{
fileMgr = [NSFileManager defaultManager];
homeDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

return homeDir;


}

at this point, i always get an exception that my data is
NIL
:

[request addRequestHeader:@"Md5Hash" value:[data MD5]];


i checked, thereĀ“s no File but i dunno why! I created that file before with:

NSMutableString *xml = [[NSMutableString alloc] initWithString:[xmlWriter toString]];

NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:
NSMutableString *fileName = [NSMutableString stringWithFormat:@"%@/7-speed-",
documentsDirectory];

[xml writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];


Solved it by:

[xml writeToFile:fileName
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];

Answer

check file exists:

if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
   NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
   NSLog(@"File not exits");
}
Comments