iOS - Write to (or read from) file failure - ios

Here is my code:
-(NSArray *)getSpecialArray:(NSString *)day{
NSString *stringURL = [NSString stringWithFormat:#"%#/%#%#", #"http://www.myDomain.com/", day, #".txt"];;
stringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSString *filePath;
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/Area/%#%#", documentsDirectory, day, #".txt"];
[urlData writeToFile:filePath atomically:YES];
}
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
if(content == nil){
content = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
content = [content stringByReplacingOccurrencesOfString:#"Main Menu\n" withString:#""];
splitData = [content componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\n\n"]];
return splitData;
}
What seems to be happening is that the write to file section is not working. Content seems to always == nil on that line. It also could be that it is writing just fine and it's not reading the file well for whatever reason, though I'm leaning towards the former option. Anyone see any problems with this code? Assume this is the first time running this code and the folder and file being written to doesn't exist. This problem seemed to occur right after switching to Mountain Lion and upgrading Xcode.

The problem is in creating the URL.
NSString *stringURL = [NSString stringWithFormat:#"%#/%#%#", #"http://www.myDomain.com/", day, #".txt"];
You are appending "/" in formatter as well as with URL value.
So your final URL will become http://www.myDomain.com//filename.txt. This is a invalid URL.
Correct it by removing "/" from either of place.
NSString *stringURL = [NSString stringWithFormat:#"%#%#%#", #"http://www.myDomain.com/", day, #".txt"];

At first, check if your file is actually created on filesystem and/or check returning value of [urlData writeToFile:filePath atomically:YES]; call.
If file exists and method returns YES, then the problem is in the reading data. Pass NSError** to stringWithContentsOfFile: encoding: error: and check it. Also, don't use NULL for objects, instead use nil.

Related

how to write json file in ios

Here i am reading and writing a json file.
Reading is done correctly but while i am writing a file it doesn't write data in json file.
Here is my code.
//reading Json file....
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bookmark" ofType:#"json"];
NSData *content = [[NSData alloc] initWithContentsOfFile:filePath];
NSArray *bookmarkJson=[NSJSONSerialization JSONObjectWithData:content options:0 error:nil];
//this contains array's of dictionary....
NSDictionary *newBookmark=#{#"index":#"1.1.1.1",#"text":#"Header",#"htmlpage":#"page_name"};
//take new array to add data with previous one
NSMutableArray *temp=[[NSMutableArray alloc]initWithArray:bookmarkJson];
// add object to new array...
[temp insertObject:newBookmark atIndex:0];
//now serialize temp data....
NSData *serialzedData=[NSJSONSerialization dataWithJSONObject:temp options:0 error:nil];
NSString *saveBookmark = [[NSString alloc] initWithBytes:[serialzedData bytes] length:[serialzedData length] encoding:NSUTF8StringEncoding];
//now i write json file.....
[saveBookmark writeToFile:#"bookmark.json" atomically:YES encoding:NSUTF8StringEncoding error:nil];
In "saveBookmark" (NSString)object i got correct file format but in bookmark.json file i didn't got any new values.
Please help me with this......
EDIT: As correctly pointed out by #IulianOnofrei, use the document directory to read/write files and not the resources directory.
Use these methods to read and write data, and your problem should be solved:
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// The main act...
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
Code courtesy from another SO answer found here: Writing and reading text files on the iPhone
And of course, the first time you try to read this file from the documents directory you won't get anything, so maybe the first step would be to copy the file there if it does not exist.
Hope this helps.

How To Down and store the Text File on Local Cache

I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:#"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:#"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];
NSLog(#"%#",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:NULL];
iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
NSLog(#"error: %#", error)
}

iOS 8 writeToFile in Simulator

I'm trying to write a simple string to file, using the following code:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSString *content = #"Test Content";
NSError *error = nil;
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(#"Error %# %#", fileName, error);
But the file is'nt written and error is null.
I'm running the code in the iOS Simulator and expect the file to be written to a location like: /Users/user/Library/Developer/CoreSimulator/Devices/85DDC17D-A771-40D9-99BE-71FF6B60D2DF/data/Containers/Data/Application/BD30A945-25DB-4ECE-B7F7-E9C20C6691C7/Documents/textfile.txt (the Path of fileName from NSLog).
As #rckoenes pointed out it was an error in the rest of my code. I have a function that deletes all files in "documents", i just didn't remember that i had this function and because of the length of the code (>5000 lines) it was hard to find. Thank you all!
working with URLs is a bit reliable way, so I would re-work your idea slightly like e.g. this:
NSURL *_documentFolder = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *_fileURL = [_documentFolder URLByAppendingPathComponent:#"textFile.txt"];
NSError *_error = nil;
BOOL _success = [#"hello!" writeToURL:_fileURL atomically:TRUE encoding:NSUTF8StringEncoding error:&_error];
that works perfectly on simulator and on real device too, and the file textFile.txt will have the content hello!.
NOTE: if the _success value is FALSE, you can get more information about the reason via a the _error, even if you'd just log it to the debug-console. I have not isolated the NSString in my example, but you can replace it with your own instance.
please check below code:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:#"textfile.txt"];
NSString *temp = [[NSString alloc] initWithString:#"Test Content"];
[temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

iOS - initWithContentsOfURL downloading old version of file

My app downloads text files from a server in order to determine the content of the files. There's one problem, I am changing the files on the server, editing their content, but when the app downloads them the files have no changed. Loading the files up in a browser shows that the changes did take effect. Somehow the app is accessing an older version of the file that shouldn't exist. Here's my code:
-(NSArray *)writeFile:(NSString *)section :(NSString *)item{
NSString *fileName = [NSString stringWithFormat:#"http://myurl.com/%#/%#.txt", section, item];
fileName = [fileName stringByReplacingOccurrencesOfString:#" "
withString:#"%20"];
NSString *data = [[NSString alloc] initWithContentsOfURL: [NSURL URLWithString: fileName] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"Read from file: %#", fileName);
NSLog(#"Content: %#", data);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt", item]];
[data writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray * arrayData = [content componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"\n\n"]
];
return arrayData;
}
There's one file that is only a single character, a number, and THAT file downloads correctly each time. The rest of the files are larger with multiple lines. When I move the files to a different server they will download the correct version of the files, but if I make changes again and try to redownload from the new source, the changes are not reflected in the download (but still on the server).
I am so confused, I can't see any reason that it would do this, unless it's saving some form of a cookie. Ideas?
It was phone's fault. I was using my Note 3 as a wireless hotspot because the normal wifi connection's range is 20 feet away from where I sit. Once I hooked up to a traditional wifi, it worked just fine.

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);
}

Resources