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];
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 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
I am new to iOS and just started learning. I have created an App for downloading files into Documents folder of the directory. When I download the files on simulator, I can find it through the path : /Users/......./Simulator/iOS7.0/Applications/Documents.
But I am not able to find the files when I run the App on the device and download the files. I have given the path using the following code:
filePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: #"Documents/%#", self.downloadedFilename]];
Can anyone please tell me the way to find the files on the device using iTunes?
How about just downloading all the files from the sandbox to your Mac? Open Xcode, Window->Organizer.
Click on the Applications entry for the connected device, and click on your Application in the list of apps. Now you can see the data files on the device for that app, and you can download the whole bundle from the device to your Mac.
Use below sample code for create and write data with in created folder document
NSData *data = [[NSData alloc] initWithBytes:saves length:4]; //replace with your file content
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *appFile = [dataPath stringByAppendingPathComponent:#"MyFile"];
[data writeToFile:appFile atomically:YES];
Update: Did you check this bool in your info.plist before connect it with itunes.? Check this bool in your info.plist to share files with itunes. Refer UIFileSharingEnabled and see this picture below.
I have my App create a file, compress it into a .zip file, then attach it to an email. But the .zip file contains many directories before the actual file. Starting with the '/' which is a nameless folder and looks invisible to the people receiving it. The top level directory is '/', the next level is 'com'...
/var/mobile/Applications/CDA16BB231BDABABBA/Documents/data.txt
How can I remove all the directories and have the .zip file contain only the file?
Here's the code I have used...
NSError *error;
NSString *documentsDirectory = [NSHomeDirectory()
stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory
stringByAppendingPathComponent:#"data.txt"];
NSLog(#"string to write:%#",printString);
[printString writeToFile:filePath atomically:YES
encoding:NSUTF8StringEncoding error:&error];
////ZIP FILE/////
NSString *zipfilePath = [documentsDirectory stringByAppendingPathComponent:#"data.zip"];
[[NSFileManager defaultManager] removeItemAtPath: zipfilePath error: &error];
ZipFile *zipFile = [[ZipFile alloc]initWithFileName:zipfilePath mode:ZipFileModeCreate];
NSDictionary *attributes = [[NSFileManager defaultManager]attributesOfItemAtPath:zipfilePath error:&error];
NSDate *Date = [attributes objectForKey:NSFileCreationDate];
ZipWriteStream *stream = [zipFile writeFileInZipWithName:filePath fileDate:Date compressionLevel:ZipCompressionLevelBest];
NSData *data = [NSData dataWithContentsOfFile:filePath];
[stream writeData:data];
[stream finishedWriting];
[zipFile close];
The problem is that you are saying:
writeFileInZipWithName:filePath
The variable filePath contains that huge long name you are complaining about. It is the whole path from the top all the way down to your actual file.
Your file's name is #"data.txt", so what you want to say is:
writeFileInZipWithName:#"data.txt"
So in my app I have a bunch of data that I'd like to write to a log file, and then display it within a UITextView when I click a button. I know how to toggle the UITextView, but I have no idea how to create and update a log file (in the local filesystem). Thanks for any help.
The basic idea is that you create the file, and append to it every time you log a new line. You can do it quite easily like this:
Writing to the file:
NSString *content = #"This is my log";
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"myFileName.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];
Reading:
//get file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"myFileName.txt"];
//read the whole file as a single string
NSString *content = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
I thought was a class out there to do this automatically as after no luck created my own.
NSLogger is a lightweight class for iOS versions 3.0 and above. It allows developers to easily log different 'events' over time which are locally stored as a .txt file.
https://github.com/northernspark/NSLogger