saving text to a file inside app [duplicate] - ios

This question already has answers here:
Writing and reading text files on the iPhone
(2 answers)
Closed 9 years ago.
Right, I've seen solutions like this before, but nine that seem to do the trick. I want to save text from a Text Field into a file in Supporting Files.
Preferably, I want it to be an HTML file, and I want it there because I want to open it again in a Web View.
I know how to do the loading, its just the saving.
The question: How do I save text from a Text Field into a file inside the Supporting Files directory?

Try something like this:
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString *theString = #"The text to write";
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileAtPath = [filePath stringByAppendingPathComponent:#"data.txt"];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
[[theString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}

Problem Solved (HTML) !!!
try this code,
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentDirectory stringByAppendingPathComponent:#"myfile.html"];
NSString *textFromTextField = textField.text;
NSString *finalText = [NSString stringWithFormat:#"<html><body>%#</body><html>",textFromTextField];
[finalText writeToFile:#"" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

Related

How to view Sqlite database ios

I am developing one iOS app in that I am using sqlite database.I have inserted records in database now I want to see that records.I searched in Library->Application Support->iPhone simulator, But in iPhone simulator folder nothing is present.So is there any another way to view sqlite database records.
Please help me,
Thank you.
This is my code for file path
-(NSString *)filePath
{
NSString *documentDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
return [documentDir stringByAppendingPathComponent:#"Test.sqlite"];
}
Now you can have your Simulator folder as "Core Simulator" not as "iPhone simulator"
Use the following Code.
// Get the Sqlite Data from the url in a NSData Object
NSData *sqlData = [[NSData alloc] initWithContentsOfURL:[
NSURL URLWithString:[sqlUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
// Store the Data locally as Sqlite File
NSString *resourceDocPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [resourceDocPath
stringByAppendingPathComponent:#"Test.sqlite"];
[sqlData writeToFile:filePath atomically:YES];
NSLog(#"File Path: %#", filePath);
In Console as:
File Path:
/Users/Library/Developer/CoreSimulator/Devices/3C0492CE-2C27-48D8-AB04-7B7EFDB77228/data/Containers/Data/Application/91AF3E65-D0C2-4CC9-A7F6-35DD32AB1FD0/Documents/Test.sqlite
Now You can easily go to your database file path and open it where ever you want.
You can achieve this by using a simple code and opening the Sqlite file in to a simple Sqlite Client like chrome extension(SqliteManager), Firefox Extension and Navicat Premium.
Code:
-(NSString *)GetDocumentDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
return documentsDir;
}
-(NSString *)getDBPath
{
NSString *documentsDir = [self GetDocumentDirectory];
return [documentsDir stringByAppendingPathComponent:#"YourSqliteFileName.sqlite"];
}
Call it like this
NSString *dbPath = [self getDBPath];
NSLog(#"Database Path = %#",dbPath);
Note: Every time you will run your application on simulator, Every time a new path is created which will be different from your previous path so you have to just copy paste this path and open it in any Sqlite Client.

Proper way to giving name to file when [NSData writeToFile:] used

I'm using that code to save downloaded videos from internet to application document folder:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *save_it = [documentsDirectory stringByAppendingPathComponent:video_filename];
NSError *error;
BOOL success = [fileData writeToFile:save_it options:0 error:&error];
if (!success) {
NSLog(#"writeToFile failed with error %#", error);
}
it works, but if there is a slash "/" in the video_filename it breaks because of slash is directory seperator, I know.
For example when video_filename is : Best Video / Best Song Ever.3gpp , log says:
{NSFilePath=/Users/Apple/Library/Developer/CoreSimulator/Devices/5A7D36F5-6EDB-495D-9E8E-B9EB22E5357C/data/Containers/Data/Application/B1D0AC48-D84C-4A0D-9F09-08BF4C45DD32/Documents/Best Video / Best Song Ever.3gpp, NSUnderlyingError=0x7d339430 "The operation couldn’t be completed. No such file or directory"}
I don't know is there any other special character that will make crashing,
So what is the best way of cleaning these special characters from nsstring ?
We can make SEO friendly urls in PHP, I'm searching a function like that to do this.
The first problem I see here is that your file path includes some spaces. in the example you gave, the value of video_filename variable is "Best Video / Best Song Ever.3gpp" which includes spaces around the slash. You first have to delete the spaces, this might help you do that:
NSArray *components = [video_filename componentsSeparatedByString:#"/"];
for (NSInteger i = 0, i < components.count, ++i) {
NSString *string = components[i];
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
components[i] = string;
}
NSString *path = [components componentsJoinedByString:#"/"];
If I understood correctly, your video_filename might be either in the form xxx.3gpp or yyy/xxx.3gpp. If it's the format of yyyy/xxxx.3gpp, you first have to create a directory named yyyy and then save the file to that directory.
This might help you do that:
- (void)createDirectory:(NSString *)directoryName
atFilePath:(NSString *)filePath
{
NSString *filePathAndDir = [filePath
stringByAppendingPathComponent:directoryName];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDir
withIntermediateDirectories:NO
attributes:nil
error:&error]) {
NSLog(#"Create directory error: %#", error);
}
}
and the way you would use this is
[self createDirectory:components[0] atFilePath:documentsDirectory];
hope this helps!
So if your filename is actually "Best Video / Best Song Ever.3gpp" I am sorry but nothing easy comes to mind.
Now if Best Video is a folder where you will save your file you can use :
+(NSString*) getPathToFolder:(NSString*) folderName {
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:folderName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:folderPath]) {
NSLog(#"Creating a new folder at\n%#", folderPath) ;
[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:nil];
}
return folderPath ;
}
This will check if your folder exist or not, if it does not exists then it will create it.
it will return the path you will want to use to save your file.
Now regarding the naming of the files, using spaces is highly unadvisable, I suggest using :
NSString* pathWITHSpaces ;
NSString* pathWithoutSpaces = [pathWITHSpaces stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps a bit

read/write from a .txt file iOS 7 objc

I have this code:
NSString *studentList = _textIn.text;
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:#"ClassOne.txt"];
[studentList writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
NSLog(#"%#", studentList);
NSLog(#"students 1 saved");
I try to write to a text file on the phone system. When I try to read from that file with:
NSError *error;
NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
pathForResource: #"classOne" ofType: #"txt"] encoding:NSUTF8StringEncoding error:&error];
_textIn.text = strFileContent;
The textfield comes up blank. The NSLog prints what was in the text field but when I try to load it up later the textfield is empty. how do I get the textfield to display what is in the file.
The writing part is alright. You are trying to read the file from your application main bundle instead of your original file path.

Convert a plist file to text

This is not a question, but a solution i was puzzled with.
The solution might also help other guys visiting SO having the same problem.
In a iOS game I made I used the plist format to store the level game data.
Now I am into making a level editor for this game, with the purpose to share the game data with close friends or the rest off the world.
It took me a couple of hours to find a solution and i like to share it with you now.
The solution was so simple that i have overlooked a possible solution.
Here it is,
Just open the plist file as a text file and you are good to go, So simple!
See example below, hope this will help some one else.
-(NSString *) levelFilePath{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [NSString stringWithFormat:#"%#%#%#", [path objectAtIndex:0],mm_HomeDirectory,mm_SubDirectory];
NSString *levelName = [levelnameStr stringByAppendingString:#".plist"];
return [documentDirectory stringByAppendingPathComponent:levelName];
NSLog(#"Level-Document %#",levelName);
}
-(void) ReadLevelFileAsText{
NSString *LevfilePath = [self levelFilePath];
NSString *textFile;
if ([[NSFileManager defaultManager] fileExistsAtPath:LevfilePath]) {
textFile = [NSString stringWithContentsOfFile:LevfilePath
encoding:NSUTF8StringEncoding
error:NULL];
} else {
NSLog(#"filePath does not exists: %#",LevfilePath);
}
NSLog(#"Content of File: %#", textFile);
}
Greetings,
J Sneek

writing string to txt file in objective c

Pulling my hair out trying to work this out. i want to read and write a list of numbers to a txt file within my project. however [string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error] doesnt appear to write anything to the file. I can see there is the path string returns a file path so it seems to have found it, but just doesnt appear to write anything to the file.
+(void)WriteProductIdToWishList:(NSNumber*)productId {
for (NSString* s in [self GetProductsFromWishList]) {
if([s isEqualToString:[productId stringValue]]) {
//exists already
return;
}
}
NSString *string = [NSString stringWithFormat:#"%#:",productId]; // your string
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSError *error = nil;
[string writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error.localizedFailureReason);
// path to your .txt file
// Open output file in append mode:
}
EDIT: path shows as /var/mobile/Applications/CFC1ECEC-2A3D-457D-8BDF-639B79B13429/newAR.app/WishList.txt so does exist. But reading it back with:
NSString *path = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
returns nothing but an empty string.
You're trying to write to a location that is inside your application bundle, which cannot be modified as the bundle is read-only. You need to find a location (in your application's sandbox) that is writeable, and then you'll get the behavior you expect when you call string:WriteToFile:.
Often an application will read a resource from the bundle the first time it's run, copy said file to a suitable location (try the documents folder or temporary folder), and then proceed to modify the file.
So, for example, something along these lines:
// Path for original file in bundle..
NSString *originalPath = [[NSBundle mainBundle] pathForResource:#"WishList" ofType:#"txt"];
NSURL *originalURL = [NSURL URLWithString:originalPath];
// Destination for file that is writeable
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *documentsURL = [NSURL URLWithString:documentsDirectory];
NSString *fileNameComponent = [[originalPath pathComponents] lastObject];
NSURL *destinationURL = [documentsURL URLByAppendingPathComponent:fileNameComponent];
// Copy file to new location
NSError *anError;
[[NSFileManager defaultManager] copyItemAtURL:originalURL
toURL:destinationURL
error:&anError];
// Now you can write to the file....
NSString *string = [NSString stringWithFormat:#"%#:", yourString];
NSError *writeError = nil;
[string writeToFile:destinationURL atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", writeError.localizedFailureReason);
Moving forward (assuming you want to continue to modify the file over time), you'll need to evaluate if the file already exists in the user's document folder, making sure to only copy the file from the bundle when required (otherwise you'll overwrite your modified file with the original bundle copy every time).
To escape from all the hassle with writing to a file in a specific directory, use the NSUserDefaults class to store/retrieve a key-value pair. That way you'd still have hair when you're 64.

Resources