I'm trying to make a txt log file with the actions that happens in my app. I want to save some text whenever the app is connecting to the server o displaying new info.
Well, how do I write to a file? I've tried using the method writeToFile: but it's not working because fileExistsAtPath: is returning NO.
My code is:
NSString *file_path = #"mylog.txt";
NSString *log = #"Hello World!!\n";
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
Thanks!
PS: Oh, would it be readable through Organizer with the iPhone plugged in?
You should use the < App_Home >/Documents folder for storing Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file_Path = [documentsDirectory stringByAppendingPathComponent:#"log.txt"];
[log writeToFile:file_path atomically:YES encoding:NSUnicodeStringEncoding error:nil];
But normally if you want to see and dump things while running the app,
you could just use NSLog() which outputs it in the console.
Try this method I wrote:
+(NSString*)createPath:(NSString*)fileName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localizedPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",fileName]];
//NSLog(#"%#",localizedPath);
return localizedPath;
}
It will return you a path for your file. You only need to give it a name.
Related
I am getting various format of documents with extension as .png,.txt,.jpg,,mp3 etc as NSData formatt, I need to store these locally and view it ,I have tried this
NSData* conData = [convStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"the converted string to nsdata is :%#",conData);
[conData writeToFile:#"Filename.txt" atomically:YES];
but unfortunately this is not working can any one help.
Note - writing NSData into a file is an IO operation which may block your main thread use dispatch, also provide file path for writing instead file name only.
This writes file for me
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Filename.txt"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
you should pass a correct path in writeToFile method
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *targetPatch = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"Filename.text"]];
[data writeToFile:targetPatch atomically:YES];
You have given only file name(Filename.txt) not whole file path thats why your code is not working.
Check below line of code you will get idea.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"Filename.txt"];
[urlData writeToFile:filePath atomically:YES];
I use the following code to store an NSMutableArray into a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathHit = [documentsDirectory stringByAppendingPathComponent:#"hit"];
[NSKeyedArchiver archiveRootObject:self.arrayHit toFile:filePathHit];
and the code below to retrieve data from the file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePathHit = [documentsDirectory stringByAppendingPathComponent:#"hit"];
NSMutableArray *unarchivedHit = [NSKeyedUnarchiver unarchiveObjectWithFile:filePathHit];
It works fine but the file been written to seems reside there all the time, so each time I relaunch my application, it reads data from there. But what I want to achieve is the data only resides there during the application operates, and once the app's shut down the data been cleared. How can I achieve this? Thanks.
You can use NSFileManager:
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:filePathHit error:&error];
I am writing an app that can access the iOS root system, the user should be able to save files to his document directory. I am using this code to save the file to the document directory.
For Text:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
For other files:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
My problem is I can save .txt files, but not other files, If I save for example .plist files with the save text methods, the contact is replaced by the directory path of the file. When I save a picture, or any other file it isn't readable. Is there a good method to save files without destroying them?
You're calling [self.filePath writeToFile:], thus writing the contents of the filePath variable to a file.
You should do something like:
[contents writeToFile:...]
Here you have an example of saving the image:
assuming you get the content of the image into NSData object:
NSData *pngData = UIImagePNGRepresentation(image);
then write it to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Have a look into these questions for more detailed explanations:
Write a file on iOS
Save An Image To Application Documents Folder From UIView On IOS
I'm working on an app that's a bit like a notebook of typed pages.
I have a UITextView *documentText and an int currentPage to keep track of multiple pages. Back and forward buttons add 1 or subtract 1 from currentPage and then they set the text in documentText to match the new value of currentPage.
However, when I run it, nothing saves, there's just a blank text field. I think it's a problem with [saveDocs writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:NULL];
, but I'm not sure what to change, or if that's even the problem.
Anyways, here's the code I'm using to save the text:
- (IBAction)saveDocs:(id)sender {
NSString *saveDocs = documentText.text;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#-%d.txt", #"document", currentPage]];
[saveDocs writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:NULL];
[[NSUserDefaults standardUserDefaults] setInteger:currentPage forKey:#"CurrentDocument"];
}
Also, in ViewDidLoad, I'm using this code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
currentPage = [[NSUserDefaults standardUserDefaults] integerForKey:#"CurrentDocument"];
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#-%d.txt", #"document", currentPage]];
NSString* doc = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[documentText setText:doc];
Thanks for your help,
-Karl
You write with NSUnicodeStringEncoding. But you read with NSUTF8StringEncoding. Perhaps you should stick with NSUTF8StringEncoding for both writing and reading.
I want to save a text string from a file when a user presses a button. Could this file be a .plist? Then, later, I want another function to read the text from the file and turn it into a variable. How is this possible?
Snarky
Saving:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingString:#"/myFile.plist"];
//Create the file if it doesnt exists
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
NSDictionary *emptyDic = [NSDictionary dictionary];
[emptyDic writeToFile:path atomically:YES];
}
//Save the text using setObject for key or something similar, you could even use a NSArray instead
NSDictionary *dic = [[NSDictionary alloc]init];
[dic writeToFile:path atomically:YES];
Loading:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/myFile.plist", documentsDirectory];
NSString *contents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
I think you can't use a .txt file directly but I have never tried it.
If you just want to save some user default setting for future reference, check out NSUserDefaults. Easier than dealing with files if you're really just trying to save some setting.
If you really want to read a string from a file, go to your Xcode organizer, go to documentation, click on the search icon, and type in "Reading Strings From" and one of the top links will be how to read and write to files.