Parse RTF file into NSArray - objective C - ios

I'm trying to parse and English Dictionary from an RTF file into an array.
I originally had it working, but I'm not sure why it isn't now.
In the dictionary, each word is separated by a new line (\n). My code so far is:
//loading the dictionary into the file and pull the content from the file into memory
NSData *data = [NSData dataWithContentsOfFile:#"wordList.rtf"];
//convert the bytes from the file into a string
NSString *string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
//split the string around newline characters to create an array
NSArray *englishDictionary = [string componentsSeparatedByString:#"\n"];
When I try and NSLog it, it just comes up with (null)...
I've already looked at: Objective-C: Reading a file line by line
But couldn't get the answer by Yoon Lee working properly. It prints out with two back slashes at the end as well as lots of unnecessary stuff at the start!
Any help would be greatly appreciated! Cheers!

Try using a plain text (txt) file instead of rtf. RTF files contain formatting information about the text as well. Thats the unnecessary stuff that you see after reading the content.

Related

cant get 100,000+ hebrew characters into objective-c string

I have 100,000+ characters of text that need to be converted into a string so I can count the characters and display them on a page correctly, but in the text there are tons of quotations ("") and lots of commas, so it doesnt even turn into a string.
Does anyone know a way that you can ignore quotations and commas inside a NSString without having to do this \"" each time?
Here's some of the text. its english/hebrew
Psalm 30
...
Psalm 100
...
The following Psalm is not to be said on Shabbat, Festivals, the day before Pesach, Chol HaMoed Pesach, and the day of Yom Kippur
...
You say “I cant even turn the text into a string”. Since you said (in a comment) you're “just pulling it off this website”, the simplest way to do this is +[NSString stringWithContentsOfURL:encoding:error:]. This works for me:
NSURL *url = [NSURL URLWithString:#"http://opensiddur.org/wp-content/uploads/2010/08/The-Blessing-Book-Nusa%E1%B8%A5-Ha-Ari-%E1%B8%A4aBaD-3.2.txt"];
NSError *error;
NSString *text = [NSString stringWithContentsOfURL:url usedEncoding:nil error:&error];
NSLog(#"error=%# text.length=%lu", error, (unsigned long)text.length);
You can look into NSURLSession or NSURLConnection when you want to do it in a non-blocking fashion.
If you plan to distribute the text in a file (named, let's say, “blessingBook.txt”) in your app bundle, you can get the URL this way:
NSURL *url = [[NSBundle mainBundle] URLForResource:#"blessingBook" withExtension:#"txt"];
If you're loading it directly from your app bundle, you probably don't need to worry about using NSURLSession to load it in the background. You might want to do your “processing” in the background though, if it takes a while.
You can replace the punctuation or commas or what ever you want to #"" (empty string).
yourString=[yourString stringByReplacingOccurrencesOfString:#"," withString:#""];
yourString=[yourString stringByReplacingOccurrencesOfString:#":" withString:#""];
yourString=[yourString stringByReplacingOccurrencesOfString:#";" withString:#""];
What ever the text you want to replace. Replace as above.
But it is lengthy process finding un wanted quotations, commas..some characters and replace with empty string..
Hope it helps you..!

NSData to NSString not working (for use in QCComposition)

I have A NSdata value that it needs to be converted into a string.
So far my app works fine loading a QC composition from a server however, I have a warning when I tell QC to load data from server.
It loads the file just fine but is there a way to avoid this worming?
I have tried to convert data to string using
NSString* newStr = [[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
HOwever, it is giving a null location of the file
Find the way I was loading the file with wrong method the correct one is:
QCComposition *qc = [QCComposition compositionWithData:urlData];

Converting NSData to NSString returns nil

I know this question is asked before, but none of the solutions worked for me. I am trying to convert an NSData object to a NSString value. I am initing the NSString object like following:
NSString *html = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
But the html is always nil. The NSData I am trying to convert is the source code of a website. It is fairly long. This is 'NSData` I am trying to convert.
Is it the length of the data that is causing the issue? I need the source code as a string. What can I do to resolve this issue?
What I tried so far:
Tried with all encoding formats as shown in this answer.
Tried with [NSString stringWithUTF8String:[urlData bytes]];
But whatever I do produce the same result. html always is nil whatever I do.
EDIT
It was a problem with the debug console. Even when the objects had values in it, the debug console always showed nil as the value for most of the objects. However NSLog always displays the value.
It's not a problem with debugger
The problem comes from compiler optimization, compiler see that string was not directly used, and optimizes the code by removing it and directly passing it to another method.
The key of the problem : You are running project on release scheme
Solution:
Here is a small guide to switch project to the Debug scheme
1) Click on the target, and click Edit scheme...
2) Popup will be displayed
3) Click Run %Your project%
4) Open Build Configuration popup
5) Select Debug
5) Press OK
6) You are ready to Go!, now you can debug anything :)
If you are using ARC, and you just wrote the code that converts the data to a string and haven't written any code yet that actually uses the string, it will get deallocated immediately. Check whether that is what is happening. For example, what does NSLog (#"%#", html) display?
NSAttributedString *str = [[NSAttributedString alloc] initWithData:data options:#{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]}
documentAttributes:nil error:&error];
Try this one:
NSString *myString = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
Generally, conversion from NSData to NSString returns nil means there is mismatch between encoding format received from server and approach used for encoding.

Reading data from .xls/.csv files into iOS

I'm new to iOS and am trying to read the contents of a spreadsheet into an iOS array.
The spreadsheet that I'm using is a simple 3 x 2 array of numbers for the first column and text for the second. I've tried reading it in with & without column headers, in .xls, .xlsx, . cdv, .txt (unicode and delimited) but without success. The file is called "funds", and the code I'm using is:
NSData *databuffer;
NSFileHandle * file;
NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)[0];
NSString *fileDir = [docDir stringByAppendingPathComponent:#"funds.xls"];
file = [NSFileHandle fileHandleForReadingAtPath:fileDir];
if (file == nil) NSLog (#"Failed to open file");
[file seekTOOffset: 10];
databuffer = [file readDataOfLength: 5];
[file closeFile];
It finds the directory of the file but gives up at [NSFileHandle fileHandleForReadingAtPath:fileDir].
What should I be doing? I need help with confirming what file type I should use as the source, and how to read it into an array.
When this has been solved, I'm likely to need to read in large amount of data, several columns, 4k rows, a mixture of text & non-integer numbers.
Is there a format or method I should be using when the volume of data is getting to that size?
Be sure to export the data from Excel in CSV format.
It's easy to use NSFileManager to access the file:
NSString *pathName = ...; /// fill in the file's pathname
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:pathName]) {
// read the file contents, see below
}
For small files, you could just say:
NSString *lines = [NSString stringWithContentsOfFile:filePath];
and then proceed to split the string into lines, and process each line.
For large files, better have a look at some more sophisticated techniques, like in Objective-C: Reading a file line by line.
As for parsing the CSV lines, use the NSString method componentsSeparatedByString to tokenize each line, something like:
NSArray *fields = [line componentsSeparatedByString:#","];
Actually, that's also what you would use to split the file contents you read into individual lines. Just pay attention to the line feeds (CR LF or LF). You will find something in how to split a string with newlines.
There is a very popular CocoaPod / Github project that both will write and parse CSV Files. https://github.com/davedelong/CHCSVParser
You can find here: Where can I find a CSV to NSArray parser for Objective-C? quite similar problem, btw. converting CSV to JSON should help you parsing data, since JSON could be easily converted to the NSDictionary or NSArray.
I use Numbers create csv and I have problem when I add "," to table.
I use some trick to fix it.
Sorry I try to add sample code here but it too long.
https://github.com/LovePick/CSVParser-Swift

Special characters in XML attributes with NSXMLParser

I get something like the following from a third party API:
<el attr="test.
another test." />
I use NSXMLParser to read the file into my app.
However, in the delegate, the attribute gets converted to test. another test. Obviously I'd like to see it with the line breaks intact.
I initially assumed that this was a bug but, according to the XML Spec it's doing the right thing:
a whitespace character (#x20, #xD, #xA, #x9) is processed by
appending #x20 to the normalized value
(See section 3.3.3.)
What are my options? Note that it's a third party API so I can't change it, even though it's wrong.
NSData *xmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"url://"]];
NSMutableString *myXmlStr = [[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
NSRange range = [myXmlStr rangeOfString:#"\n"];
[myXmlStr replaceCharactersInRange:range withString:#"[:newline:]"];
NSData *newXmlData = [myXmlStr dataUsingEncoding:NSUTF8StringEncoding];
Just replace [:newline:] with new line character whenever u like it :)

Resources