How to convert &#8211,&#8222 etc in Objective-C - objective-c

I made server side by Python and which return some scraped html string to client side which is made by Objective-C.
But When I try to show from client side which retuned string from server , it contains &#8211,&#8222,etc.But I don't know why it contains above characters.
Do you have any idea? And I want to convert them correctly with Objective-C. Do you have any idea? Thanks in advance.

If you want to stick with Cocoa you could also try to use NSAttributedString and initWithHTML:documentAttributes:, you will lose the markup than, though:
NSData *data = [#"<html><p>&#8211 Test</p></html>" dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:nil];
NSString *result = [string string];

These are HTML Entities
Here is NSString category for HTML and here are the methods available:
- (NSString *)stringByConvertingHTMLToPlainText;
- (NSString *)stringByDecodingHTMLEntities;
- (NSString *)stringByEncodingHTMLEntities;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;

Related

Retrieving a specific data

I am new to xcode.. and I would love to learn about retrieving data from XML.. This is a draft code that I have been stucked with for days.. I manage to display a list of XML codes
XML CODE:
<find>
<set_number>038881</set_number>
<no_records>000138874</no_records>
<no_entries>000007000</no_entries>
</find>
However, now I have some difficulties in retrieving only the set_number from this xml... The URL I have left it blank due to confidential purposes.. so dont mind about it.. The last two codes has resulted my app to force close.. Help!!
NSString *URL = [NSString stringWithFormat:#""];
NSMutableData *receivedData = [[[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:URL] ]autorelease];
NSString *theRecord = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];
NSString *path = [theRecord valueForKey: #"set_number"];
NSLog(#"File Data: %#", path);
I tried to add in this code at the bottom instead..
if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?
I tried to add in this code at the bottom instead..
`if ([theRecord isEqualToString:#"no_records"]){
NSLog(#"Contents of URL: %#", theRecord);
}`
Then I also trying to debug my codes.. No error shown.. instead they display 0 for the output.. and I am wondering is it because my no_records is an integer?? But I have assign the record as a string.. is that why they couldnt display?? Please help!!
To parse your XML use the NSXMLParser class.
NSString *path = [theRecord valueForKey: #"set_number"];
theRecord is a NSString instance that can not use valueForKey.
You should parse your xml string first and get the content you want from tag.
Or you should get substring in your string.

NSCharacterSet cuts the string

I am getting lastest tweet and show it in my app. I put it in a NSMutableString and initialize that string like below in my xmlparser.m file:
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
I can get the tweet but somehow it cuts some of the tweets and shows some part of it. For example tweet is
Video games in the classroom? Social media & #technology can change education http://bit.ly/KfGViF #GOVERNING #edtech
but what it shows is:
#technology can change education http://bit.ly/KfGViF #GOVERNING #edtech
Why do you think it is? I tried to initialize currentNodeContent in other ways to but I could not solve the problem.
Do you have any idea why is this happening?
Event-driven (SAX) parsers are free to return only part of the text of a node in a callback. You might only be getting part of the tweet passed in. You should probably accumulate characters in a mutable string until you get a callback indicating the end of the element. See Listing 3 and the surrounding text in this guide.
You've got two problems here:
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
currentNodeContent = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
Simply casting an NSString to an NSMutableString doesn't work. You have to make a mutable copy yourself or initialise a new NSMutableString using the contents of an NSString.
Furthermore, the text parser is only giving you the last part of the string because it may be interpreting the '&' simply as part of an entity reference, or it may be an entity reference itself.
What you probably want to do is:
Before you begin parsing, initialise currentNodeContent so that it is an empty NSMutableString:
currentNodeContent = [NSMutableString string];
As you are parsing, append the characters to the currentNodeContent:
[currentNodeContent appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

How to get data (select's lines) from web service to xcode?

I want to get all the results of a sql table's call (select *) in php, to send them to the iphone's app and use them there.
What steps would you recommend me?
I am a complete noob in xcode and php. I have some tests like this one:
NSString *miURL = [NSString stringWithFormat:#"http://hello.com/test.php];
NSString *myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:miURL]];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *list = [NSArray alloc];
lista = [[parser objectWithString:myRawJson error:nil] copy];
And in the .php:
<?php
$conectID = mssql_connect("SERVIDOR\SQLEXPRESS","**","**");
mssql_select_db("Animals");
$result=mssql_query("select * from dbo.animals where name='jack'");
$row=mssql_fetch_array($result);
if ($row){
$myArray = array($row["name"], $row["type"], $row["colour"], $row["age"], $row["address"]);
echo json_encode($myArray);
}
All of this is good and quick for a simple line.. but for a lot of lines from a sql's select would be very inefficient, doesn't it?
Because I would like to execute for example: "select * from dbo.animals" and save each field of the table in its counterpart xcode's object's field. In xcode I would have a list of this:
#interface DataPerfil : NSObject {
NSString *name;
NSString *type;
NSString *colour;
NSInteger *age;
NSString *address;
}
....
I hope I have explained it well..
Sorry my bad english and thanks.
If you're talking real web service as in soap here is a tutorial I used :
http://www.devx.com/wireless/Article/43209/0/page/1
It's more complex than your example but the web service layer adds security and hides the access to data.

Is there a way to "auto detect" the encoding of a resource when loading it using stringFromContentsOfURL?

Is there a way to "auto detect" the encoding of a resource when loading it using stringFromContentsOfURL? The current (non-depracated) method, + (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;, wants a URL encoding. I've noticed that getting it wrong does make a difference for what I want to do. Is there a way to check this somehow and always get it right? (Right now I'm using UTF8.)
I'd try this function from the docs
Returns a string created by reading data from a given URL and returns by reference the encoding used to interpret the data.
+ (id)stringWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
this seems to guess the encoding and then returns it to you
What I normally do when converting data (encoding-less string of bytes) to a string is attempt to initialize the string using various different encodings. I would suggest trying the most limiting (charset wise) encodings like ASCII and UTF-8 first, then attempt UTF-16. If none of those are a valid encoding, you should attempt to decode the string using a fallback encoding like NSWindowsCP1252StringEncoding that will almost always work. In order to do this you need to download the page's contents using NSData so that you don't have to re-download for every encoding attempt. Your code might look like this:
NSData * urlData = [NSData dataWithContentsOfURL:aURL];
NSString * theString = [[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
if (!theString) {
theString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
if (!theString) {
theString = [[NSString alloc] initWithData:urlData encoding:NSUTF16StringEncoding];
}
if (!theString) {
theString = [[NSString alloc] initWithData:urlData NSWindowsCP1252StringEncoding];
}
// ...
// use theString here...
// ...
[theString release];

How to save a text document in Cocoa with specified NSString encoding?

I'm trying to create a simple text editor like Textedit for Mac OS X, but after many hours of research can't figure out how to correctly write my document's data to a file. I'm using the Cocoa framework and my application is document-based. Looking around in the Cocoa API I found a brief tutorial, "Building a text editor in 15 minutes" or something like this, that implements the following method to write the data to a file:
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
[textView breakUndoCoalescing];
NSAttributedString *string=[[textView textStorage] copy];
NSData *data;
NSMutableDictionary *dict=[NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
data=[string dataFromRange:NSMakeRange(0,[string length]) documentAttributes:dict error:outError];
return data;
}
This just works fine, but I'd like to let the user choose the text encoding. I guess this method uses an "automatic" encoding, but how can I write the data using a predefined encoding? I tried using the following code:
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
[textView breakUndoCoalescing];
NSAttributedString *string=[[textView textStorage] copy];
NSData *data;
NSInteger saveEncoding=[prefs integerForKey:#"saveEncoding"];
// if the saving encoding is set to "automatic"
if (saveEncoding<0) {
NSMutableDictionary *dict=[NSDictionary dictionaryWithObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
data=[string dataFromRange:NSMakeRange(0,[string length]) documentAttributes:dict error:outError];
// else use the encoding specified by the user
} else {
NSMutableDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:NSPlainTextDocumentType,NSDocumentTypeDocumentAttribute,saveEncoding,NSCharacterEncodingDocumentAttribute,nil];
data=[string dataFromRange:NSMakeRange(0,[string length]) documentAttributes:dict error:outError];
}
return data;
}
saveEncoding is -1 if the user didn't set a specific encoding, otherwise one of the encodings listed in [NSString availableStringEncodings]. But whenever I try to save my document in a different encoding from UTF8, the app crashes. The same happens when I try to encode my document with the following code:
NSString *string=[[textView textStorage] string];
data=[string dataUsingEncoding:saveEncoding];
What am I doing wrong? It would be great if someone knows how Textedit solved this problem.
Perhaps you remember that NSDictionary can only store objects...
NSMutableDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
NSPlainTextDocumentType,
NSDocumentTypeDocumentAttribute,
[NSNumber numberWithInteger:saveEncoding],
NSCharacterEncodingDocumentAttribute,
nil];