How to fix issue with unrecognized Special Character on Ipad/Iphone? - iphone

I am working on an app that gets a bunch of descriptions through xml and then after parsing puts them on the screen. I'm having a problem with some of the descriptions with apostrophes turning into question marks. What I mean is, they start out in the xml, on the output screen and in the database I get them from as an apostrophe, but then it shows up on the app as a Question mark. This doesn't always happen, but it does with the same descriptions every time. Heres an example:
This is what is in the xml/database
But it won't be easy.
After a tour of the house, you'll be
This is what shows up on the app:
But it won?t be easy.
After a tour of the house, you?ll be
I'm pretty sure that the problem is that the ipad/iphone doesn't recognize the character that it is receiving...but I have no idea how I would go about fixing it. Here is a my Parser code: I believe the xml is being sent as UTF - 8 encoding.
[whereToGetXML appendFormat:xmlID];
NSURL *URL=[[NSURL alloc] initWithString:whereToGetXML];
NSData *dataFromServer = [[NSData alloc] initWithContentsOfURL:URL];
NSLog(#"where to get xml is:%#", whereToGetXML);
// Do any additional setup after loading the view from its nib.
NSData *dataWithoutStringTag = [[NSData alloc]init];
NSXMLParser *firstParser = [[NSXMLParser alloc] initWithData: dataFromServer];
[firstParser setDelegate:self];
[firstParser parse];
//Convert the returned parsed string to data using dataUsingEncoding method. HAVE TO HAVE allowLossyConversion:YES or else it will crash on half of the states.
dataWithoutStringTag =[tempParserString dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion:YES];
NSString *htmlCode = [[NSString alloc] initWithData:dataWithoutStringTag encoding:NSASCIIStringEncoding];
NSMutableString *temp = [NSMutableString stringWithString:htmlCode];
NSData *finalData = [temp dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSXMLParser* parser = [[NSXMLParser alloc] initWithData:finalData];
// NSLog(#"Data is: %#", dataWithoutStringTag);
//NSXMLParser* parser = [[NSXMLParser alloc] initWithData: dataFromServer];
[parser setDelegate: self];
//[parser setShouldResolveExternalEntities:YES];
[parser parse];
[parser release];

It's presumably because the string isn't escaped.
Try adding a backslash before each quotation mark.
\'message\'

Related

How to handle Spanish character in my App?

In my app i have a service which supports spanish and return the result in spanish.
Now i am trying to pass some search term to this service to get the result back but its failing because while sending compiler converts the word to some funny word with unidentified characters.
I am doing this:
name here is coming in spanish but when i am adding this in the config dictionary it gets converted again to some funny thing.
-(void)perfromLocationSearchWithName:(NSString *)name{
NSData * nameCode = [[NSData alloc]init];
nameCode = [name dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString * namePass = [[NSString alloc]initWithData:nameCode encoding:NSUTF8StringEncoding];
NSLog(#"Name:%#",namePass);
NSMutableDictionary *config = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
NSString * strAction = [NSString stringWithFormat:#"vendorSearchByName"];
if (namePass !=nil){
[config setObject:namePass forKey:#"vendorName"];
//[config setObject:#"001" forKey:#"MakeCode"];
[config setObject:#"5" forKey:#"maxCount"];
[config setObject:strAction forKey:#"action"];
}
NSLog(#"Dict%#",[config description]);
comm = [[CommManager alloc] init];
[comm searchDealerLocationWithOptions:config withDelegate:self];
[namePass release];
}
Please help
Thanks,
Try using NSISOLatin1StringEncoding. Helped us in our app.

Passing archived Data through a sharedURL

I currently have two somewhat similar apps and was looking into a way to share data across the two apps. I set up a shared url and everything and can jump from one app to the other without any problem. The problem arises when I try to pass data through the url. I have a class in both apps that are identical to one another and am relying on a NSKeyedArchiver and decoder for the encoding of them and decoding as well as encoding them in strings to pass along the url.
Having access to both sides I know that the data passed from app 1 to app 2 is untainted and arrives just as app 1 encoded it. But I can't seem to decode the data on the other side!
I encode it here:
NSURL* app2=[NSURL URLWithString:#"app2://"];
if ([[UIApplication sharedApplication] canOpenURL:app2]) {
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:[tableHelper objectAtIndex:[indexPath section]]forKey:#"TempData" ];
[archiver finishEncoding];
NSString* tmp=[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding ] autorelease];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"app2://%#",[tmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
[data release];
[archiver release];
}
I then decode it as such:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
if (!url) {
return NO;
}
NSString *URLString = [url absoluteString];
NSString* dataString=[[URLString componentsSeparatedByString:#"app2://"] lastObject];
NSString* perString=[dataString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSKeyedUnarchiver* unArchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:[perString dataUsingEncoding:NSASCIIStringEncoding]];
TempItem* temp=[unArchiver decodeObjectForKey:#"TempData"];
[unArchiver finishDecoding];
//...//
}
Is there more to encoding/decoding custom classes that I am missing? I do implement NSCoding in my class the problem I think is in
[perstring dataUsingEncoding:NSASCIIStringEncoding]
as it appears to always be null?
Thanks!
I checked the output after the encoding and it is as such
bplist00Ô,-T$topX$objectsX$versionY$archiverÑXTempData©
'U$nullÖ
XitemsizeXquantityUpriceV$classYconvertedTunitQ1#?ð
and after adding percent escapes
bplist00%C3%94%01%02%03%04%05%08,-T$topX$objectsX$versionY$archiver%C3%91%06%07XTempData%C2%80%01%C2%A9%09%0A%17%18%19%1A%1B%1F'U$null%C3%96%0B%0C%0D%0E%0F%10%11%12%13%14%15%16XitemsizeXquantityUpriceV$classYconvertedTunit%C2%80%03%C2%80%05%C2%80%04%C2%80%08%C2%80%06%C2%80%02Q1%23?%C3%B0%00%00%00%00%00%00%23?%C3%B0%00%00%00%00%00%00%10%01%C3%92%1C%0E%1D%1EZNS.objects%C2%A0%C2%80%07%C3%92%20!%22&X$classesZ$classname%C2%A3%23$%25%5ENSMutableArrayWNSArrayXNSObject%5ENSMutableArray%C3%92%20!(+%C2%A2)*XTempItemXNSObjectXTempItem%12%00%01%C2%86%C2%A0_%10%0FNSKeyedArchiver%00%08%00%11%00%16%00%1F%00(%002%005%00%3E%00#%00J%00P%00%5D%00f%00o%00u%00%7C%00%C2%86%00%C2%8B%00%C2%8D%00%C2%8F%00%C2%91%00%C2%93%00%C2%95%00%C2%97%00%C2%99%00%C2%A2%00%C2%AB%00%C2%AD%00%C2%B2%00%C2%BD%00%C2%BE%00%C3%80%00%C3%85%00%C3%8E%00%C3%99%00%C3%9D%00%C3%AC%00%C3%B4%00%C3%BD%01%0C%01%11%01%14%01%1D%01&%01/%014%00%00%00%00%00%00%02%01%00%00%00%00%00%00%00.%00%00%00%00%00%00%00%00%00%00%00%00%00%00%01F
I added NSLogs on the decode portion and it is the same. I am baffled...
After fixing the misplacement of the [unArchiver finishdecoding]; I now get the error
*** -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

iPhone encoding of non latin characters

I am trying to parse a JSON response of a GET request. When the characters, are latin no problem.
However when they are not latin the message doesn't come out correctly. I tried greek and instead of "πανος" i get "& pi; & alpha; & nu; & omicron; & sigmaf;"
The code I use for parsing the response is:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response %#", responseString);
// array from the JSON string
NSArray *results = [responseString JSONValue];
When I try to read the response from a website using ajax, everything is fine. The same applies when trying to send a GET request to the application servers with data from iphone. So when i transmit data to the server and read it from the website everything is fine. When i try to show the same data in the app, "Houston we have a problem".
Any clues?
EDIT: To avoid misunderstandings, it's not an issue of HTML, I just point out that for some readon utf-8 characters here are encoded correctly and automatically eg. "&pi" will be converted to "π", however objective c doesn't seem to do this on its own
There is a confusion I think.
π is an HTML entity which is unrelated to text encoding like UTF8 / Latin.
Read wikipedia for details about...
You need a parser to decode these entities like the one previously mentioned by Chiefly Izzy:
NSString+HTML category and method stringByReplacingHTMLEntities
Look at Cocoanetics NSString+HTML category and method stringByReplacingHTMLEntities method. You can find it at:
https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSString%2BHTML.m
Here's a pretty decent list of lot of HTML entities and their corresponding unicode characters.
Try to use this snippet of code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSString *decodedString = [NSString stringWithUTF8String:[responseString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
NSLog(#"response %#", decodedString);
// array from the JSON string
NSArray *results = [decodedString JSONValue];
I have faced the same problem, but I solved it by changing the JSON parser. I have started using the SBJSONParser, and now I am getting the appropriate results. This is the code snippet, I have used
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
SBJSON *parser=[[SBJSON alloc]init];
NSArray *JSONData = (NSArray*)[parser objectWithString:returnString error:nil];

iphone: NSMutableURLRequest returns strange characters for MS Word style apostrophe

We are pulling content off our website using XML/NSMutableURLRequest and sometimes it pulls through the "curly" style apostrophe and quotes, ’ rather than '. NSMutableURLRequest seems to hate these and turns them into the strange \U00e2\U0080\U0099 string.
Is there something that I can to do prevent this? I am using the GET method, so should I be somehow telling it to use UTF-8? Or, am I missing something?
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
NSString *urlStr = [NSString stringWithFormat:#"%#",url];
NSURL *serviceUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setHTTPMethod:#"GET"];
NSURLResponse *serviceResponse;
NSError *serviceError;
app.networkActivityIndicatorVisible = NO;
return [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
NSURLConnection returns an NSData response. You can take that NSData response and turn it into a string. Then take this string, turn it back into a NSData object, properly UTF-8 encoding it along the way, and feed it to NSXMLParser.
Example: (Assuming response is the NSData response from your request)
// long variable names for descriptive purposes
NSString* xmlDataAsAString = [[[NSString alloc] initWithData:response] autorelease];
NSData* toFeedToXMLParser = [xmDataAsAString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser* parser = [[[NSXMLParser alloc] initWithData:toFeedToXMLParser] autorelease];
// now utilize parser...
I would suggest replacing those characters using stringByReplacingCharactersInRange:withString: to replace the unwanted strings.
NSString *currentTitle = #"Some string with a bunch of stuff in it.";
//Create a new range for each character.
NSRange rangeOfDash = [currentTitle rangeOfString:#"character to replace"];
NSString *location = (rangeOfDash.location != NSNotFound) ? [currentTitle substringToIndex:rangeOfDash.location] : nil;
if(location){
currentTitle = [[currentTitle stringByReplacingOccurrencesOfString:location withString:#""] mutableCopy];
}
I've done this in the past to handle the same problem you describe.
Try using the stringByReplacingPercentEscapesUsingEncoding:

How to log nsxmlparser

I'm parsing an xml from an url, by
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[rssParser parse]
How to NSLog it so as to see the xml in console??? If i use
NSLog ("%#",rssParser);
i'm showed wit 'XMLParser x 4d562' in the console
You should set parser's delegate and process retrieved xml data in its methods. See NSXMLParserDelegate protocol reference.
You can't. The NSXMLParser class never loads the entire contents of the XML stream in memory at once (that's why it's an "NSXMLParser" and not an "NSXMLDocument"). You should download the data from the URL, and use it to instantiate your RSS parser, and also to create an NSString that you log instead:
NSData *data = [NSData dataWithContentsOfURL:xmlURL];
rssParser = [[NSXMLParser alloc] initWithData:data];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data: %#", string);
[string release];
Please pay attention to the fact that the "initWithContentsOfURL:" methods are synchronous, and will block your UI thread until the data has downloaded. You might want to use ASIHTTPRequest or the NSURLConnection mechanism instead, with asynchronous connections.