iOS write to a txt [duplicate] - ios

This question already has an answer here:
How to write in a txt-file, iOS 7
(1 answer)
Closed 8 years ago.
I want to write in a txt, but my code not working...
This is my code:
-(void)bestScore{
if(cptScore > bestScore){
bestScore = cptScore;
highScore.text =[[NSString alloc] initWithFormat: #" %.d", bestScore];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bestScore" ofType:#"txt"];
NSString *test = #"test";
[test writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
}
I have already a file named bestScore.txt in my folder "Supporting Files"
Can you help me please ?
Thanks
EDIT :
I can read my file "bestScore.txt" with this code :
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bestScore" ofType:#"txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
highScore.text = textFromFile;
bestScore = [textFromFile intValue];

Try this:
-(void)bestScore{
if(cptScore > bestScore){
bestScore = cptScore;
highScore.text =[[NSString alloc] initWithFormat: #" %.d", bestScore];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Preferences/bestScore.txt"];
NSString *test = [NSString stringWithFormat:#"%#",bestStore];
NSError *error;
// save a new file with the new best score into ~/Library/Preferences/bestScore.txt
if([test writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error])
{
// wrote to file successfully
NSLog(#"succesfully wrote file to %#", filePath);
} else {
// there was a problem
NSLog(#"could not write file to %# because %#", filePath, [error localizedDescription]);
}
}
}
And to read the score back in, you can do:
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Preferences/bestScore.txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if(textFromFile)
{
highScore.text = textFromFile;
bestScore = [textFromFile intValue];
} else {
// if the file doesn't exist or if there's an error, initialize bestScore to zero
bestScore = 0;
highScore.text = #"";
}

Related

How to concatenate/merge data of three textfiles into one textfiles in iOS

I'm having a big trouble. I'd like to concatenate data of multiple textfiles into another textfiles. But I cannot. can you help me ? Many thanks
Read each file one by one,
NSString *firstFileContent = [NSString stringWithContentsOfFile:<your file path>
encoding:NSASCIIStringEncoding
error:nil];
//Similarly read other files, and store them in secondFileContent and thirdFileContent.
//now concatenate all to form one big string.
NSString *bigString = [NSString stringWithFormat:#"-First File- \n%# \n-Second File- \n%#\n-Third File-\n%#",firstFileContent, secondFileContent, thirdFileContent];
//write to file, create a new one
[bigString writeToFile:<path to write>
atomically:YES
encoding:NSASCIIStringEncoding
error:nil];
Edit 1 :
As per your comment that your file is in DocumentDirectory use this code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:<your file name>];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
First load content of file in NSString and use following code:
NSString *strConcatenate = [NSString stringWithFormat:#"%# %# %#", textfiles1, textfiles2, textfiles3];
NSLog(#"%#", strConcatenate);
You just have to load the content of the files into NSMutableString and concatenate them :
NSMutableString *myString = #"Content of the first file";
NSString *test = [myString stringByAppendingString:#" content of the second file"];
You need to read the text files in from the bundle and then append them, once you have that then write it back out. I wrote this example and I hope you can learn from it.
NSMutableString *mutableString = [[NSMutableString alloc] init];
NSArray *textFiles = #[ #"textfile1", #"textfile2", #"textfile3" ];
for (NSString *textFileName in textFiles) {
NSString *path = [[NSBundle mainBundle] pathForResource:textFileName
ofType:#"txt"];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (content) {
[mutableString appendFormat:#"%#\n", content];
} else {
NSLog(#"%#", error.localizedDescription);
}
}
NSLog(#"%#", mutableString);
NSError *error = nil;
BOOL result = [mutableString writeToFile:#"concatenated_file.txt" atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!result) {
NSLog(#"%#", error.localizedDescription);
}

saving udid string to a text file

hi i'm working on a simple activation app in iOS. i want to save udid in a text file and equal text file with current udid but i can't save udid to text file
NSString *udid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"h" ofType:#"txt"]];
NSMutableString *text = [NSMutableString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
NSLog(#"text is : %#",text);
NSString *text1 = text;
NSString *y;
if ([text1 isEqualToString:y]) {
[text appendString:udid];
NSString *myURLString = [fileURL absoluteString];
[text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil];
NSLog(#"saved to file : %#",text);
}else {
if ([text isEqualToString:udid]) {
NSLog(#"yes thats it");
lable.text = #"yes thats it";
}else {
NSLog(#"nononono");
exit(0);
}
}
There's a few problems with your code. Starting with:
if ([text1 isEqualToString:y]) {
where is "y" defined or declared?
Also, you never look at the error parameter while writing to a file. Change this:
[text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil];
to this:
NSError *error;
BOOL success = [text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:&error];
if(NO == success)
{
NSLog(#"error from writing to %# is %#", myURLString, [error localizedDescription]);
}
And you might have a better clue as to what kind of error you're running into.
Lastly, with your comment, you've made it clear you're trying to write a file directly into the bundle of your application. Which is a big (sandboxed) no no.
Instead of:
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"h" ofType:#"txt"]];
do this instead:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = [paths firstObject];
NSURL *fileURL = [NSURL fileURLWithPath:[basePath stringByAppendingString:#"/h.txt"]];
and this will save your file into the Documents directory, which is a legal place to save files.

Text File to NSArray

I have a text file that I download at launch from my website. It saves it to the Documents directory in the app. I want to read and process that text file and turn it into an NSArray.
I tried this:
- (NSArray *)articleReason {
NSString *filename3 = #"GameList.txt";
NSArray *pathArray3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory3 = [pathArray3 objectAtIndex:0];
NSString *yourSoundPath3 = [documentsDirectory3 stringByAppendingPathComponent:filename3];
NSURL *url = [NSURL fileURLWithPath:yourSoundPath3 isDirectory:NO];
NSString *urlData = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [urlData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSIndexSet *indexes = [parsed indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSRange range = [(NSString *)obj rangeOfString:#"Reason:"];
if (range.location != NSNotFound)
{
return YES;
}
return NO;
}];
NSArray *disallowed = [parsed objectsAtIndexes:indexes];
NSString * myString = [disallowed componentsJoinedByString:#" "];
disallowed = [myString componentsSeparatedByString:#"Reason: "];
return disallowed;
}
This does not work. The thing is, if I download the text file while making the NSArray, it ends up working. Here's that code:
- (NSArray *)articleReason {
NSString *stringURL = kGameURL;
NSURL *url = [NSURL URLWithString:stringURL];
NSString *urlData = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [urlData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSIndexSet *indexes = [parsed indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSRange range = [(NSString *)obj rangeOfString:#"Reason:"];
if (range.location != NSNotFound)
{
return YES;
}
return NO;
}];
NSArray *disallowed = [parsed objectsAtIndexes:indexes];
NSString * myString = [disallowed componentsJoinedByString:#" "];
disallowed = [myString componentsSeparatedByString:#"Reason: "];
return disallowed;
}
Any idea why this is not working? I verified in the Documents directory that the text file is downloading correctly. I do the downloading of the file in didFinishLaunching in the App Delegate. Here's that code:
NSString *stringURL2 = kGameURL;
NSURL *url2 = [NSURL URLWithString:stringURL2];
NSString *urlData2 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];
NSFileManager *fileManager2 = [NSFileManager defaultManager];
NSString *docsDirectory2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path2 = [docsDirectory2 stringByAppendingPathComponent:#"GameList.txt"];
[urlData2 writeToFile:path2 atomically:YES ];
Any help would be greatly appreciated.
Figured it out.
[urlData2 writeToFile:path2 atomically:YES ];
Writeto file needed it include the encoding.

Ziparchive not working for unzip in iphone

I am working on zip and unzip object, and for that, I am using ziparchive classes ,I am able to zip files but problem occurs while unzipping of file ,following is my code
NSString *str1;
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFile];
NSLog(#"this is my whole new ipad%d",pictureArr.count);
[self calculation];
for (int i=0;i<[pictureArr count]; i++) {
NSString *str = [NSString stringWithFormat:#"%#",[pictureArr objectAtIndex:i]];
NSLog(#"This is my whole new ipad%#",[pictureArr objectAtIndex:i]);
[za addFileToZip:str newname:[pictureArr objectAtIndex:i]];
}
//NSString *textPath = [cachePath stringByAppendingPathComponent:#"text.txt"];
NSString *strUrl = [NSString stringWithString:path];
NSString *strunzip=[docspath stringByAppendingPathComponent:strUrl];
NSLog(#"This is my new file path for strXmlName%#",docspath);
[za addFileToZip:strUrl newname:strXmlName];
NSString *fileContent = [docspath stringByAppendingPathComponent:#"strXmlName.zip"];
NSLog(#"This is my final path for%#",fileContent);
NSString *updateURL = [[NSBundle mainBundle] pathForResource:fileContent ofType:#"zip" inDirectory:#"res"];
if ([za UnzipOpenFile:fileContent]) {
if ([za UnzipFileTo:docspath overWrite:NO]) {
NSLog(#"Archive unzip success");
[fileManager removeItemAtPath:docspath error:NULL];
}
else {
NSLog(#"Failure to unzip archive");
}
/*7405726724,9227669500-agile infoway
*/
}
else {
NSLog(#"Failure to open archive");
}
NSData *unzipData = [NSData dataWithContentsOfFile:fileContent];
fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:docspath contents:unzipData attributes:nil];
NSLog(#"This is my file");
[za UnzipOpenFile:path];
BOOL success = [za CloseZipFile2];
NSLog(#"Zipped file with result %d",success);
but it directly goes out from if ([za UnzipOpenFile:fileContent]) i dont know why its happning,
what i have tried is this
and this
so please guide me
thanks

How can I return all the name of the files in Resources folder in ios?

I want to retrieve in an array of the name of the files in Resources folder that have the .html extension. I have done this:
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Resources"];
NSError *error = nil;
NSArray *documentArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
for (int i=0; i < [documentArray count] - 1; i++) {
NSLog(#"value %#", [documentArray objectAtIndex:i]);
}
But the for loop displays continously null. Anyone knows how can I get this task right? thank you
Don't use NSHomeDirectory. Use [[NSBundle mainBundle] resourcePath] to get path to app's resources.
Edited: here's your example code.
NSString *resPath = [[NSBundle mainBundle] resourcePath];
NSError *error = nil;
NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resPath error:&error];
if (!error)
{
for (NSString * filename in filenames)
{
NSString *extension = [filename pathExtension];
if ([extension isEqualToString:#"html"])
{
NSLog(#"%#", filename);
}
}
}

Resources