Writing data to a file on the device and reading it from the device (iPhone)

What is the easiest way to programmatically create a file.txt file on your device and then write some data in the application and then send this data to your computer?

I assume that the last part can be performed programmatically in the same way as using any program on your computer to receive data from the device.

So far i'm doing something like this

NSFileHandle *infile;
NSFileManager *fm;
fm=[NSFileManager defaultManager];
NSString *strings=[@"/Downloads/file.txt" stringByExpandingTildeInPath];

if (![fm fileExistsAtPath:strings]) {
 [fm createFileAtPath:strings contents:nil attributes:nil];
 infile=[NSFileHandle fileHandleForWritingAtPath:strings];
 [infile writeData:[[NSString stringWithFormat:@"lalala japierdole\n", [NSDate date]] dataUsingEncoding:NSUTF8StringEncoding]];
}else {
 infile=[NSFileHandle fileHandleForWritingAtPath:strings];
 [infile seekToEndOfFile];
}
[infile writeData:[[NSString stringWithFormat:@"lulukukuioio.\n", [NSDate date]] dataUsingEncoding:NSUTF8StringEncoding]];

It is just creating a file if it does not exist and writes some data, but I have a problem with the outline. This code works fine when I work with my simulator, when I try it on my device, then I really don’t know if I can even create a file and how to get from it later.

+3
1

API :

NSData *data = [NSData dataWithContentsOfFile:path];
[data writeToFile:path atomically:NO];

, , , . :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ( paths.count > 0 )
{
  NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"file.txt"];
  NSData *data = [NSData dataWithContentsOfFile:path];
  ...
}
+6

All Articles