Convert formatted HTML text string to NSString parts - iphone

I want to decode HTML string and store it in NSString.
following is the html string for one of the response from google direction api.
teststring is Turn <b>right</b> onto <b>Kennington Park Rd/A3</b><div style="font-size:0.9em">Continue to follow A3</div><div style="font-size:0.9em">Entering toll zone in 1.7 km at Newington Causeway/A3</div><div style="font-size:0.9em">Go through 2 roundabouts</div>
I want to store this html string in Array of 4 different NSStrings with following 4 NSStrings (removing all information for size colour)
Turn right onto Kennington Park Rd/A3
Continue to follow A3
Entering toll zone in 1.7 km at Newington Causeway/A3
Go through 2 roundabouts
I have used following method to convert html string to plain text.(html_response is the response from server and stringByConvertingHTMLToPlainText is the method defined in custom class file)
testString = (NSString*) [html_response stringByConvertingHTMLToPlainText];
NSLog(#"%#",testString);
but it converts whole string instead of breaking it in parts.
output at the console is
Turn right onto Kennington Park Rd/A3Continue to follow A3 Entering toll zone in 1.7 km at Newington Causeway/A3 Go through 2 roundabouts
So do I need to write custom method to do this? Any help will be greatly appreciated.

There's a very nice NSString category that you can use, it's a part of the project MWFeedParser. More specifically, you look for the file NSString+HTML.
The NSString+HTML category adds the following methods to the NSString Class,
- (NSString *)stringByStrippingTags;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;
- (NSString *)stringByDecodingHTMLEntities;
- (NSString *)stringByEncodingHTMLEntities;
You could then try something like:
NSString *summary = [[[htmlString stringByStrippingTags] stringByRemovingNewLinesAndWhitespace] stringByDecodingHTMLEntities];
Hope it helps!, good luck :)

Related

How To Parse CSV Data

I want to parse CSV data, which is downloaded to the app. Right now I have the following data - "SPY",186.33,"3/17/2014","4:00pm",**+1.67**,185.59,186.77,185.51,93784328. I used NSLog to display it on the console. What I want to do is read the 1.67 (or whatever it may be) and turn it into an NSString. The url where I get the information from will be consistent, but the numbers will change day to day. Thanks in advance!
If you're able to capture the row of data as a string (which it sounds like you've done, since you're able to NSLog it to the console), then you should be able to split the string apart like so:
NSArray *stringComponents = [yourDataRow componentsSeparatedByString:#","];
NSString *desiredComponent = [stringComponents objectAtIndex:4];
Then, your +1.67 (or whatever) will be available as desiredComponent.
Note: This solution assumes that the +1.67 component of the row will always occupy the 5th position in the row.
I use CHCSVParser by Dave DeLong, it supports parsing this format from a file, NSString, or NSInputStream. Probably your best bet! https://github.com/davedelong/CHCSVParser

Speed Up Label Text change in iOS

My program works
send byte using CocoaAsyncSocket (TCP)
get response (byte data)
change byte array to valid data (int / nsstring / etc)
change label text with it(step 3)
I put a NSLog and watched. Log shows almost fast and my function (change label text) runs well. However, I can see change label`s text on simulator about 4~5 second later then function called.
My first way is this
get a byte array - split into nsdata - change to nsstring - input array - get string - add sub string (like '000%' or '000 sec') - change label text
And Second is
get a byte array - split - change to nsstring - call a function (add sub string - change label text)
Well... How can I boost its change speed?
Changing the label text should happen "almost instantly", and when it takes this long it is usually caused by not updating the label text on the main thread. It is a UIKit object, therefore it must only be modified on the main thread.
Use:
dispatch_async(dispatch_get_main_queue(), ^{
self.label.text = myString;
});
I had a similar problem when fetching events from the Calendar with almost an identical delay. If what Inafziger suggested doesn't work for you, I suggest using performSelectorOnMainThread: and call a method to update your labels in your "Step 3."
[self performSelectorOnMainThread:#selector(yourMethodToUpdateLabels) withObject:nil waitUntilDone:NO];
It worked great for my situation. Hope it helps. :)

Loading text from a file

I am making an Iphone drinking card game app.
All the card mean something different and i want the user to be able to press an info button and then show a new screen with information about the current card. How can i make a document to load text from instead of using a bunch og long strings?
Thanks
You could look into plist files - they can be loaded quite easily into the various collection objects and edited with the plist editor in Xcode.
For instance, if you organize your data as a dictionary, the convenience constructor
+ (id)dictionaryWithContentsOfURL:(NSURL *)aURL
from NSDictionary would provide you with as many easily accessible strings as you need.
This method is useful if you consider your strings primarily data as opposed to UI elements.
Update:
As #Alex Nichol suggested, here is how you can do it in practice:
To create a plist file:
In your Xcode project, for instance in the Supporting Files group, select New File > Resource > Property List
You can save the file in en.lproj, to aid in localization
In the Property list editing pane, select Add Row (or just hit return)
Enter a key name (for instance user1) and a value (for instance "Joe")
To read the contents:
NSURL *plistURL = [[NSBundle mainBundle] URLForResource:#"Property List" withExtension:#"plist"];
NSLog(#"URL: %#", plistURL);
NSDictionary *strings = [NSDictionary dictionaryWithContentsOfURL:plistURL];
NSString *user1 = [strings objectForKey:#"user1"];
NSLog(#"User 1: %#", user1);
A plist, a JSON string, and an SQLite database walked into a bar ...
Oops!! I mean those are the three most obvious alternatives. The JSON string is probably the easiest to create and "transport", though it's most practical to load the entire thing into an NSDictionary and/or NSArray, vs read from the file as each string is accessed.
The SQLite DB is the most general, and most speed/storage efficient for a very large number (thousands) of strings, but it takes some effort to set it up.
In my other answer, I suggest the use of a dictionary if your texts are mostly to be considered as data. However, if your strings are UI elements (alert texts, window titles, etc.) you might want to look into strings files and NSBundle's support for them.
Strings files are ideally suited for localization, the format is explained here.
To read them into you app, use something like this:
NSString *text1 = NSLocalizedStringFromTable(#"TEXT1", #"myStringsFile", #"Comment");
If you call your file Localizable.strings, you can even use a simpler form:
NSString *str1 = NSLocalizedString(#"String1", #"Comment on String1");
A useful discussion here - a bit old, but still useful.

get element value

I have a NSString like that? (in iPhone application)
NSString *xmlStr = "<?xml version=1.0 encoding=UTF-8>
<information>
<name>John</name>
<id>435346534</id>
<phone>045635456</phone>
<address>New York</address>
</information>"
How I can get elements value?
(Do i need convert to XML format and get elements value? or split string? any way please tell me?)
Thank you guys.
If you want to use split string, you can use tokenization of strings using "componentsSeparatedByString" method. This is a more cumbersome method of course, rather than the recommended XMLParser
To get the name.
NSArray *xmlStr_first_array = [xmlStr componentsSeparatedByString: #"<name>"];
NSString *xmlStr_split = [NSString stringWithFormat:#"%#",[xmlStr_first_array objectAtIndex:1]];
NSArray *xmlStr_second_array = [xmlStr_split componentsSeparatedByString: #"</name>"];
NSString *name = [NSString stringWithFormat:#"%#",[xmlStr_second_array objectAtIndex:0]];
The most obvious solution is to use an XML parser to retrieve the values from each element.
You could use the excellent TBXML for this task. It provides a really simple interface where it wouldn't take more than a few lines to retrieve the desired values. The drawback to using this small library is that it (as far as I know) loads the entire XML data into memory. In this particular case, however, that is not problem at all.
There's of course also the option of using the NSXMLParser, though this is an event-driven parser, and thus a bit less simple to use.
Your string is in xml format already and you need to parse it to retrieve data. There're several options available - for example you can use NSXMLParser class or libxml library.
Edit: XMLPerformance sample project shows how to use both approaches and compare their performance.

Parsing a .txt or html file into a string in the iPhone SDK

So, what I'm trying to do, is take a .txt or html file, being able to search through it, and grab a piece of text from file, place it into a string and finally adding it into a textView.
Each couple of piece of text will be divided like this:
001:001 Text1
001:002 Text2
001:003 Text3
002:001 Text1a
002:002 Text1b
... and so on
So essentially you would search the text for those numbers, and it would grab the text only. Is there a way to do that using objective C and using it on a iPhone app?
Use
NSString *pathToDefaultPlist = [[NSBundle mainBundle] pathForResource:#"TextFile" ofType:#"text"];
to load text file. Then:
+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error
this function to load the text file in String. Then use NSString function to divide the token :)
In addition to the [NSString stringWithContentsOfFile:encoding:error] to get the text of the file, your textView should have a setStringValue method.
so I'd do something like this:
NSString *pathToTextFile;
NSError *readError;
NSString *fileData = [NSString stringWithContentsOfFile:pathToTextFile
encoding:(appropriate encoding for your file)
error:*readError]
[textView setStringValue:fileData];
This might need a little massaging, I'm at work and don't have my Mac to verify the method signatures etc. But that's the general idea.