I am working on app where I need to display arabic text from a text file. I am using following code:
NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
NSLog(#"%#",[lines objectAtIndex:0]);
I get about 60 records in this array lines. But when I try to print the data it does not print anything.
If the file starts with a newline, the first element in lines will be just an empty string. Try printing out the whole array instead, just to verify that your code is working as intended:
NSLog(#"%#", lines);
Related
NSDictionary *allDatDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *responseData = [allDatDictionary objectForKey:#"responseData"];
NSDictionary *arrayOfResult = [responseData objectForKey:#"results"];
for (NSDictionary *diction in arrayOfResult) {
NSString *title = [diction objectForKey:#"title"];
NSString *content = [diction objectForKey:#"content"];
NSString *url = [diction objectForKey:#"url"];
[array addObject:title];
[content1 addObject:content];
[url1 addObject:url];
NSLog(#"title: %#, \n Content: %# \n, Url: %# \n", [diction objectForKey:#"title"], [diction objectForKey:#"content"],[diction objectForKey:#"url"]);
NSString *text = #"";
text = [NSString stringWithFormat:#"Title: %#%#\nURL: %#\nContent: %#\n\n", text, [diction objectForKey:#"title"],[diction objectForKey:#"url"],[diction objectForKey:#"content"]];
Hey guys, I got the json and I need to show title, content and url on screen. I don't need table ranting like this just show on screen. NSLog shows everything but when I try to write on a UILabel it just shows 1 result. Any tips how I can do that? thanks
You're setting labelTitle's text in a for loop, so you're only going to see the last result, because you keep changing it each time thru the loop. If you want to see all of the results, you'll have to build up a string that contains all of them and then set that as the text of the label.
At the top of the for loop, declare an NSString variable and set it to #"", like the following:
NSString *text = #"";
Then each time thru the loop, instead of setting the label text to your string, build up this string that you're saving at the top, like the following:
text = [NSString stringWithFormat:#"%#%#\n", text, [diction objectForKey:#"title"]];
You can see how I modified that format string. It takes the previous text you've saved, adds to it your new title, and then adds a carriage return.
As an alternative, you could have an NSMutableArray at the top, and add your strings to that array each time you go thru the for loop. Then at the end, you can use the NSArray method componentsJoinedByString:, using a carriage return as the separator, to get an NSString containing all of the individual strings that you added to the array.
After you have this one string, using either of these methods, you can set that as the text on the label.
Is it possible to delete a line of text that store in .txt file. I am currently successful to extract each line inside txt file and add into array then display each line in TableView. Now I if I want to delete particular line How do I do it?
Put the strings from your NSArray into a NSMutableArray, delete the line that you want deleted, convert to a single NSString by joining elements with #"\n" string, and then write the string to file, like this:
NSMutableArray *tmp = [myArray mutableCopy];
[tmp removeObjectAtIndex:indexToRemove];
NSString *tmpStr = [NSString componentsJoinedByString:#"\n"];
NSError *err = nil;
[tmpStr writeToFile:myFile
atomically:NO
encoding:NSUTF8StringEncoding // <== use an encoding that you need
error:&err];
I have a file with many lines separated by "\n". One of the lines is:
Christian Grundekjøn
I can't read the file unless I delete the line. I use the following code to read line by line:
for (NSString *line in [[NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:NULL] componentsSeparatedByString:#"\n"])
If I don't delete the line, the code wouldn't even go into the for loop at all. Nothing was read. How to handle the non-English letters?
If you are generating the text file from within iOS then you need to make sure you are encoding it with NSUTF8StringEncoding. But given the problem you are reporting, I suspect that you may be pulling in data from another source and that source hasn't encoded the text as UTF8. If this is the case, you may be able to fix the problem outside your app but converting the source file to UTF8.
If you don't know what encoding is used, e.g. because the user has supplied the file, iOS can try to guess it for you. A pattern that I have used successfully is to first try to get the string using UTF8 encoding, for example using the same approach you use. Assuming you write a method, to which you pass a filename, to get the string something like the following:
- (NSString*) stringFromFile: (NSString*) filePath;
{
NSError* error = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: fileName
encoding: NSUTF8StringEncoding
error: &error];
if (stringFromFile) return stringFromFile; // success
NSLog(#"String is not UTF8 encoded. Error: %#", [error localizedDescription]);
NSStringEncoding encoding = 0;
NSError* usedEncodingError = nil;
NSString* stringFromFile = [NSString stringWithContentsOfFile: path
usedEncoding: &encoding
error: &usedEncodingError];
if (stringFromFile)
{
NSLog(#"Retrieved string using an alternative encoding. Encoding was: %d", encoding);
return stringFromFile;
}
// either handle error or attempt further explicit unencodings here
return nil;
}
In many cases, usedEncoding works very well. But there are edge cases where trying to figure out an encoding can be very tricky. It all depends on the source file.
I had problem with Japanese characters. My solution was when saving file to doc directory
NSString *fileData = [NSString stringWithFormat:#"%#", noteContent];
BOOL isWriteToFile = [fileData writeToFile:notePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
When reading file content
[[NSString alloc] initWithContentsOfFile:fullNotePath usedEncoding:nil error:nil];
In the file, store your data in unicode format or you can also store special character in unicode format.
I'm trying to write a csv file. I have two arrays at hand - one with the titles (Name, Number etc), another with the actual values (Jon, 123 ...).
Now, after the following two operations:
[[titles componentsJoinedByString:#", "] writeToFile:file atomically:YES];
[[values componentsJoinedByString:#", "] writeToFile:file atomically:YES];
only the values array is written to the file. I realise that I may need to open the file again, but how do I do that after writing the first array? Or what is it exactly that I'm doing wrong if this is not the case?
Thanks!
The second line is in fact overwriting the file you wrote in the first line. One simple way to get around this problem would be to simply append the second string to the first (likely with an '\n' in between since you're making a csv file) and writing that string to your file:
NSString *str1 = [[titles componentsJoinedByString:#", "];
NSString *str2 = [[values componentsJoinedByString:#", "];
NSString *outputStr = [str1 stringByAppendingFormat:#"\n%#", str2];
[outputStr writeToFile:file atomically:YES];
Second time it replaces the old contents. So you could read the old content, append the old content with the new content and save on file.
Write first row
[[titles componentsJoinedByString:#", "] writeToFile:file atomically:YES];
Where you need to add another row every time
NSString *previousContent = [[NSString alloc] initWithContentsOfFile:file usedEncoding:nil error:nil];
NSString *str2 = [[values componentsJoinedByString:#", "];
NSString *outputStr = [previousContent stringByAppendingFormat:#"\n%#", str2];
[outputStr writeToFile:file atomically:YES];
I need to parse a text file, one line at a time. Also, is there EOF in Objective-C?
Something like this might work for you:
NSString *fileContents = [NSString stringWithContentsOfFile:#"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
This will give you an array where each element is a line of the string.
Objective-C is a proper extension of C. Any C program is a valid Objective-C program. Among other things, this means that EOF defined in the standard C header "stdio.h" is an EOF marker in Objective-C as well.
stringWithContentsOfFile is deprecated.
Here is an updated answer:
NSError* error;
NSString *fileContent = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:&error];
NSArray *lines = [fileContent componentsSeparatedByString:#"\n"];