how to convert into NSString? - iphone

I am stuck with utf-8 to NSString. I am getting this data from web service :
{
Description = "漢字仮名交じり文";
Images =
(
{
imageName = "0_25_07_2012_10_32_54_1343212374.jpg";
}
);
Time = "11:00 am";
actId = 290;
actTitle = "漢字仮名交じり文";
}
Now how can i convert 名 (名) this kind of code to NSString?

I'm pretty sure something is wrong with your web service. If the web service response is JSON or XML data, then the JSON or XML parser should have decoded the special characters. Since it did not, the web service mistakenly uses a double decoding of characters outside the ASCII range.
The best solution is to fix it at the source, i.e. in the web service.
If you can't, then use the stringByDecodingHTMLEntities method from this NSString category, e.g.:
NSString* textValue = [response objectForKey: #"Description"];
textValue = [textValue stringByDecodingHTMLEntities];
You will have to run each string property through this method.

The codes that you have here are called numeric character references. They have nothing directly to do with UTF8 in general.
See this question for a summary of answers to your problem

Related

Parsing & to & in json in iphone

I have following json response.. here i displayed only few lines of it.
How can I replace "&" with & and store in an array.
Thanks in advance.
[
{
"cat_id": "1",
"cat_name": "Dining & Nightlife",
"0": {
"subcat_id": "2",
"subcat_name": "Restaurants"
},
"1": {
"subcat_id": "3",
"subcat_name": "Bar & Club"
}
}
]
Your JSON data isn't properly encoded. In addition to the JSON format, all the strings seem to be HTML encoded. This is a double encoding, which is completely unnecessary.
I strongly recommend you fix this at the source, i.e. on the server. Then you have proper JSON data that can be used without problems by many different clients.
If you cannot fix it on the server, then you have to decode each string attribute in the JSON response. Before you do that, you better investigate if only ampersands are affected (unlikely) or other special characters (such as < > ä ô) as well. Then you can add this to your question and we will likely be able to help you.
Update:
I don't quite understand what classes you're using to keep the parsed JSON data in memory. (You mention arrays.) But to fix the double encoded ampersands, use the following code on each string:
str = [str stringByReplacingOccurrencesOfString: #"&" withString: #"&"];
try this
NSString *sting=[[NSString alloc]init];
sting=[[request responseString] stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSDictionary *resDict =[parser objectWithString:sting error:nil];
U have to do in take array. and using for loop u can replace &amp to & and that string add in array. and make new araay...

Subscript and Superscripts in CDATA of an xml file. Using UILabel to display the parsed XML contents

I need to display subscripts and superscripts (only arabic numerals) within a UILabel. The data is taken from an XML file. Here is the snippet of XML file:
<text><![CDATA[Hello World X\u00B2 World Hello]]></text>
Its supposed to display X2 (2 as superscript). When I read the string from the NSXMLParser and display it in the UILabel, it displays it as X\u00B2. Any ideas on how to make it work?
I think you can do something like this, assuming the CDATA contents have been read into an NSString and passed into this function:
-(NSString *)removeUnicodeEscapes:(NSString *)stringWithUnicodeEscapes {
unichar codeValue;
NSMutableString *result = [stringWithUnicodeEscapes mutableCopy];
NSRange unicodeLocation = [result rangeOfString:#"\\u"];
while (unicodeLocation.location != NSNotFound) {
// Get the 4-character hex code
NSRange charCodeRange = NSMakeRange(unicodeLocation.location + 2, 4);
NSString *charCode = [result substringWithRange:charCodeRange];
[[NSScanner scannerWithString:charCode] scanHexInt:&codeValue];
// Convert it to an NSString and replace in original string
NSString *unicodeChar = [NSString stringWithFormat:%C", codeValue];
NSRange replacementRange = NSMakeRange(unicodeLocation.location, 6);
[result replaceCharactersInRange:replacementRange withString:unicodeChar];
unicodeLocation = [result rangeOfString:#"\\u"];
}
return result;
}
I haven't had a chance to try this out, but I think the basic approach would work
\u00B2 is not any sort of XML encoding for characters. Apparently your data source has defined their own encoding scheme (which, frankly, is pretty stupid as XML is capable of encoding these directly, using entities outside of CDATA blocks).
In any case, you'll have to write your own parser that handles \u#### and converts that to the correct character.
I asked the question to my colleague and he gave me a nice and simple workaround. Am describing it here, in case others also get stuck at this.
Firstly goto this link. It has a list of all subscripts and superscripts. For example, in my case, I clicked on "superscript 0". In the following HTML page detailing "superscript 0", goto "Java Data" section and copy the "⁰". You can either place this directly in XML or write a simple regex in obj-c to replace \u00B2 with "⁰". And you will get nice X⁰. Do the same fro anyother superscript or subscript that you might want to display.

Junk character in Webview

I am getting html content as a string in my webservice response which contains "&nbsp" in it. When I display that data in webview, "&nbsp" is converted in junk character. Please let me know how to solve it.
You have to read the string as NSUTF8 encoded string and then pass the string to web view using "loadHTML" method mentioned in UIWebView.
Not only that, if you want to display special characters like copy right, double quotes etc or other language characters in the HTML, you have to use UTF8 encoding.
Use the stringByReplacingPercentEscapesUsingEncoding: method of NSString
like :
NSString *decoded = [yourString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Also to remove use
[yourString stringByReplacingOccurrencesOfString:#" " withString:#" "];
stringByReplacingOccurrencesOfString is deprecated from ios 9
let decoded = yourString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

String manipulation in objective-c

this is hard to describe but I am currently catching a string from a database, this string can be 1-4 characters long, however I am wanting to always display 4 characters, so if i get say a string back that is 34, i want it to be 0034.
I have set up a method to catch the string so now I just need to figure out how to do this. what I then plan to do is feed that string into a NSArray so I can send each [i'th] of the array off to 4 differetn methods that control animations in my app.
The reason its in string format is because I have had to bounce it round from hex, to int to string for various formatting reasons within the application.
this is my code i have so far. Suggestions/solutions would be great thankyou, I am so new its hard to find solutions for stuff like string manipulation etc..
//... other method I am getting the string from/.
[self formatMyNumber:dataString];
///..
-(void)formatMyNumber:(NSString *)numberString{
//resultLabel.text = numberString; //check to make sure string makes it to here.
//NSLog(#"hello From formatMyNumber method"); //check
}
//..
//the with send off each character to 4 animation methods that accept integers.
- (void)playAnimationToNumber:(int)number{
//...
//UpDated... weird stuff happening.
here is my method so far.
//Number Formatter
-(void)formatMyNumber:(NSString *)numberString{
NSLog(#"This is what is passed into the method%#",numberString);
int tempInt = (int)numberString;
NSLog(#"This is after I cast the string to an int %i",tempInt);
//[NSString alloc] stringWithFormat:#"%04d", numberString];
NSString *tempString = [[NSString alloc] initWithFormat:#"%04d", tempInt];
NSLog(#"This is after I try to put zeros infront %#",tempString);
//resultLabel.text = tempString;
//NSLog(#"hello From formatMyNumber method");
}
this is the output.
[Session started at 2011-06-19
16:18:45 +1200.] 2011-06-19
16:18:54.615 nissanCode0.1[4298:207]
731 2011-06-19 16:18:54.616
nissanCode0.1[4298:207] 79043536
2011-06-19 16:18:54.617
nissanCode0.1[4298:207] 79043536
2011-06-19 16:18:54.617
nissanCode0.1[4298:207] hello From
formatMyNumber method
As far as the number of zeros preceding your string goes there are a couple of ways to do this. I'd suggest:
NSString *myString = [NSString stringWithFormat:#"%04d",[dataString intValue]];
Is it possible you could have the number in integer form instead of string form? If so, it's pretty easy to use [NSString stringWithFormat:#"%04d", number]. See here for a list of the possible format specifiers.
See what stringWithFormat: can do. I realize you mentioned your numbers are NSStrings, but if they were ints, or you convert them back to ints, the following may do the trick. Modify the following to best suit your need:
return [NSString stringWithFormat:#"%04d", number];

iPhone SDK - stringWithContentsOfUrl ASCII characters in HTML source

When I fetch the source of any web page, no matter the encoding I use, I always end up with &# - characters (such as © or ®) instead of the actual characters themselves. This goes for foreign characters as well (such as åäö in swedish), which I have to parse from "&Aring" and such).
I'm using
+stringWithContentsOfUrl: encoding: error;
to fetch the source and have tried several different encodings such as NSUTF8StringEncoding and NSASCIIStringEncoding, but nothing seems to affect the end result string.
Any ideas / tips / solution is greatly appreciated! I'd rather not have to implement the entire ASCII table and replace all occurrances of every character... Thanks in advance!
Regards
I'm using
+stringWithContentsOfUrl: encoding: error;
to fetch the source and have tried several different encodings such as NSUTF8StringEncoding and NSASCIIStringEncoding, but nothing seems to affect the end result string.
You're misunderstanding the purpose of that encoding: argument. The method needs to convert bytes into characters somehow; the encoding tells it what sequences of bytes describe which characters. You need to make sure the encoding matches that of the resource data.
The entity references are an SGML/XML thing. SGML and XML are not encodings; they are markup language syntaxes. stringWithContentsOfURL:encoding:error: and its cousins do not attempt to parse sequences of characters (syntax) in any way, which is what they would have to do to convert one sequence of characters (an entity reference) into a different one (the entity, in practice meaning single character, that is referenced).
You can convert the entity references to un-escaped characters using the CFXMLCreateStringByUnescapingEntities function. It takes a CFString, which an NSString is (toll-free bridging), and returns a CFString, which is an NSString.
Are you sure they originally are not in Å form? Try to view the source code in a browser first.
That really, really sucks. I wanted to convert it directly and the above solution isn't really a good one, so I just wrote my own ascii-table converter (static) class. Works as it should have worked natively (though I have to fill in the ascii table myself...)
Ideas for optimization? ("ASCII" is a static NSDictionary)
#implementation InternetHelper
+(NSString *)HTMLSourceFromUrlWithString:(NSString *)str convertASCII:(BOOL)state
{
NSURL *url = [NSURL URLWithString:str];
NSString *source = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
if (state)
source = [InternetHelper ConvertASCIICharactersInString:source];
return source;
}
+(NSString *)ConvertASCIICharactersInString:(NSString *)str
{
NSString *ret = [NSString stringWithString:str];
if (!ASCII)
{
NSString *path = [[NSBundle mainBundle] pathForResource:kASCIICharacterTableFilename ofType:kFileFormat];
ASCII = [[NSDictionary alloc] initWithContentsOfFile:path];
}
for (id key in ASCII)
{
ret = [ret stringByReplacingOccurrencesOfString:key withString:[ASCII objectForKey:key]];
}
return ret;
}
#end