I am writing a registration app that is supposed to save a CSV file in the documents directory folder. I would like to look at the output and see what happens when I open the CSV file in excel. I navigated to the documents directory folder by finding out where it should be saved using this code snippet:
NSLog(#"Info Saved");
NSLog(#"Documents Directory: %#", [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject]);
Here is my code for saving the information put into the 11 text fields in the registration form:
- (IBAction)saveFormButton:(id)sender {
// saves text field data in comma separated CSV file format
NSString *formData = [NSString stringWithFormat:#"%#,%#,%#,%#,%#,%#,%#,%#,%#,%#,%#\n",
self.nameTextfield.text, self.emailTextfield.text,
self.phoneTextfield.text, self.termTextfield.text,
self.schoolTextfield.text, self.graduationTextfield.text,
self.gpaTextfield.text, self.degreeTextfield.text,
self.interestTextfield.text, self.groupTextfield.text,
self.appliedTextfield.text];
// get document directory path
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)objectAtIndex:0];
// append results.csv onto doc path
NSString *event = [documentDirectoryPath stringByAppendingString:#"results.csv"];
// creates folder if it does not exist
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:event];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[formData dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
Should I be seeing a file in that specific folder I have navigated to?
Thank you for your help,
Change this line:
NSString *event = [documentDirectoryPath stringByAppendingString:#"results.csv"];
to:
NSString *event = [documentDirectoryPath stringByAppendingPathComponent:#"results.csv"];
This makes sure that the path is correctly formatted. Also, you seem to be checking to see if "documentDirectoryPath" exists before creating the file rather than the filename itself. Change:
if (![[NSFileManager defaultManager] fileExistsAtPath:documentDirectoryPath]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
to:
if (![[NSFileManager defaultManager] fileExistsAtPath:event]) {
[[NSFileManager defaultManager] createFileAtPath:event contents:nil attributes:nil];
}
Here is a more elegant way with less code
// Content of file
NSString* str= #"str,hey,so,good";
// Writing
NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:#"file.csv"];
[str writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
// Reading
NSString *string = [[NSString alloc] initWithContentsOfFile:root encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#",string);
The result:
2015-07-15 15:52:56.267 ObjC[2927:15828] str,hey,so,good
Related
I'm writing an application for the Apple watch. I'm using the following method (from this SE answer) to write to a log file:
- (void) writeLogWith: (NSString *) content {
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"whathappened.md"];
//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
[[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];
//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];
return;
}
I'm running it by plugging in my phone and running it directly on my watch. The function is definitely executing (I've stepped thought with the debugger) and it also knows that the file exists and doesn't repeatedly try and create it.
Xcode tells me that the file information is:
Printing description of documentsDirectory:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents
Printing description of documentsDirectory:
(NSString *) documentsDirectory = 0x16d66890
Printing description of fileName:
(NSString *) fileName = 0x16d66950
Printing description of fileName:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents/whathappened.md
I'd like to know if it's writing things correctly, but when I look at the container (following these SE answers), the documents directory is empty.
My question is: where did my file go? And how can I find it?
I think what might be giving you problems is the NSFileHandle object. I have written thousands upon thousands of files to the documents folder and I have never used NSFileHandle to do this. Simply use the built in method on NSString to write your string to the file path.
Try this:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[documentsDirectory stringByAppendingPathComponent:#"whathappened"] stringByAppendingPathExtension:#"md"];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
NSString *string = #"The String You Want To Write.";
NSError *error;
[string writeToFile:filePath atomically:false encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"There was an error writing file\n%#", error.localizedDescription);
}
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSLog(#"File exists :)");
}
else {
NSLog(#"File does not exist :(");
}
From other research, the answer appears to be:
If you are storing a file on the Apple Watch, it is stored in it's own container, which isn't visible via xcode.
It indeed, appears to be related to this bug report: https://openradar.appspot.com/radar?id=5021353337946112, found via this SE: How to export shared container of an iOS App with Xcode6.2?
I am trying to upload sqlite file on iCloud. I am using NSFileCoortinator for coping the file from one file to another file but schema of sqlite file is only get copied, I am not getting data in sqlite file….Also sometimes the data is appearing in the sqlite file on iCloud. I don’t understand why this is happening. Is this sqlite file issue or I did wrong in code. If anyone has solution please help me out.
-(void)uploadFile
{
//-------code for uploading data to icloud
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject]
NSString *str=[NSString stringWithFormat:#"%#/XMPPMessageArchiving.sqlite",applicationSupportDirectory]; //copy this file
NSString *fileName = [NSString stringWithFormat:#"XMPPMessageArchiving.sqlite"];
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
NSURL *fromURL = [NSURL fileURLWithPath:str];
NSURL *toURL = [[ubiq URLByAppendingPathComponent:#"Documents"]
URLByAppendingPathComponent:fileName];;
[coordinator coordinateReadingItemAtURL:fromURL options:0 writingItemAtURL:toURL options:NSFileCoordinatorWritingForReplacing error:nil byAccessor:^(NSURL *newReadingURL, NSURL *newWritingURL)
{
NSError *error=nil;
NSData *data = [[NSFileManager defaultManager] contentsAtPath:fromURL.path];
//if file is already present on icloud replace that file with new file
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:newWritingURL.path];
if (fileExists)
{
[[NSFileManager defaultManager] removeItemAtPath:toURL.path error:NULL];
}
BOOL isCopied= [[NSFileManager defaultManager] copyItemAtPath:newReadingURL.path toPath:newWritingURL.path error:nil];
NSLog(#"file copied= %d",isCopied);
}];
}
The value for file copied is always 1 but still data is not available.
I was having trouble to read a txt file in my app. I was able to write the file but i could not read the file i've just written. So i searched for some tutorials and decided to create a separated sample. But it still not working.
Here is the code i am using :
- (IBAction)gerarArquivo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:#"%#,%#\n",#"teste1",#"teste2"];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *surveys = [docPath stringByAppendingPathComponent:#"results.csv"];
if (![[NSFileManager defaultManager] fileExistsAtPath:surveys]) {
[[NSFileManager defaultManager] createFileAtPath:surveys contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:surveys];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
NSLog(#"Foi");
}
- (IBAction)recuperarArquivo:(id)sender {
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *surveys = [docPath stringByAppendingPathComponent:#"results.csv"];
if ([[NSFileManager defaultManager] fileExistsAtPath:#"/results.csv"])
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:surveys];
NSString *surveyResults = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding];
[fileHandle closeFile];
NSLog(surveyResults);
}
}
Your reading code has an if statement containing:
[[NSFileManager defaultManager] fileExistsAtPath:#"/results.csv"]
which is unlikely to work due to the supplied path (should be fileExistsAtPath:surveys), and if that doesn't work then you won't ever try to read the file contents.
i want to create folder in document directory and want to save images in that folder. i have tried but the folder and the images are storing in document directory..But i want to store the images inside the folder.my code is working fine but the images are not saving inside Folder..
NSError *error;
NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:#"Folder"];
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSInteger anIndex = 0;
for (UIImage *anImage in _chosenImages)
{
NSString *anImageName = [NSString stringWithFormat:#"%d.png", anIndex++];
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", aDocumentsDirectory, anImageName];
NSLog(#"the path is=%#",anImagePath);
NSData *anImageData = UIImagePNGRepresentation(anImage);
[anImageData writeToFile:anImagePath atomically:YES];
}
I guess your "anImagePath" is still pointing to documents directory.
edit it as "dataPath" as the argument as below
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", dataPath, anImageName];
try this..
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
actually you arr passing NO in "withIntermediateDirectories" parameter, and if you pass NO to this than if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.
I created a text file in ios and it is stored in Data files in following location.Sandbox => Documents => mylogfile.txt.
This file is updates only when I connected my Device with Mac and Xcode only.If I eject the device, and connect again to see the updated text file. It is not updated. It will be same as old file. The log file does not updated when disconnected from PC.
How to update text file on all time.
My Code:
-(void)logme:(NSString *)mymessage
{
NSString *content = mymessage;
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"locationlog.txt"];
//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
[[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];
//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];
}
and called this log file like,
[self logme:myHTML];