Convert Unicode character to NSString - iphone

I have received string from webservice which contains Unicode character. I want to convert that To plain NSString. so How can i do that?
ex: "This isn\u0092t your bike"
So how can remove unicode and replace it with its equal special symbol characted.
The output would be : "This isn't your bike"

char cString[] = "This isn\u2019t your bike";
NSData *data = [NSData dataWithBytes:cString length:strlen(cString)];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"result string: %#", string);
This should work.
UPDATE FOR THE COMMENT:
The unicode character specified by you is not supported in all fonts.
http://www.fileformat.info/info/unicode/char/92/fontsupport.htm
But this one does.
http://www.fileformat.info/info/unicode/char/2019/fontsupport.htm
Thats why it throws an error.

NSString *final_url = [NSString stringWithFormat:url];
final_url = [final_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:final_url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:120.0];
NSURLResponse *response;
NSError *error = [[NSError alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *objJSON = [SBJSON new];
NSMutableDictionary *objDataDic = [objJSON objectWithString:strResponse error:nil];

There is a library which does conversion
https://github.com/alexaubry/HTMLString. It will convert all kind of Unicode character.
let escapedSnack = "Fish & Chips"
let snack = escapedSnack.removingHTMLEntities // "Fish & Chips"

Related

Not getting json response in google query of longitude and latitude in iOS?

I am new to iOS, so if any help it will be appreciated.
I am trying to get the longitude and latitude from address, earlier the code was working fine but now the JSON data are coming null.
Here my sample code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"my Coordinate : %#",returnString);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
But i am getting the output as null.
So please help me out.
Thanks!
Thanks for your replies that all make me learn a lots.
As one of my friend just tell me the solution so i am sharing with you.
Here is the code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *locationResult = [parser objectWithString:returnString];
//[reverseGeoString copy]`
And its working fine.
But still there is a question that why this happen.As earlier that code is working fine but it suddenly stopped working.
You must construct your returnString in the following method that actually receives the data:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
Check out this for additional information on how to use NSURLConnection and the delegate methods.
I would say you're missing the all-important "REQUEST"...
This is what I do. Hope it helps:
NSString *encodedAddress = (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge_retained CFStringRef)searchBar.text, NULL, (CFStringRef) #"!*'();:#&=+$,/?%#[]",kCFStringEncodingUTF8 );
NSString* searchURL = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true",encodedAddress];
NSError* error = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error){
NSLog(#"Error performing request %#", searchURL);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (jsonString!=nil){
NSLog(#"%#",jsonString);
}

Parsing NSData from GET request

I made NSData from GET request.
NSString *nameID = [[NSString alloc]initWithString: #"1"];
NSString *urlString = [NSString stringWithFormat:#"http://www.xxxxx.com/news/index.php?id=%#",
[nameID stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSData *urlData;
NSURLResponse *response;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
NSString *results = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",urlData);
And then how to parse that? I've got only something like:
2011-10-21 19:27:06.213 httptest[1674:207] <3c21444f 43545950 45206874 6d6c2050 55424c49 4320222d 2f2f5733 432f2f44 54442058 48544d4c
You are logging urlData (an NSData object) instead of results (the NSString). NSData objects are displayed in the output console as hex digit pairs. If you log 'results' you will see something like:
<!DOCTYPE http...
which is probably what you were expecting.
you have already converted the resulting data to a NSString
at first you have to define what that data is: XML- or JSON-String? or Binary-encoded stuff? and then you have to write your own parser or choose one you like.
I assume that your result is xml and lets just assume that you want to use the TBXML-Dom-Parser. then try:
NSString *results = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
TBXML * tbxml = [TBXML tbxmlWithXmlString:result];
TBXMLElement *rootElement = tbxml.rootElement;
TBXMLElement *childELement = [TBXML childElementNamed:#"myChildTag" parentElement:rootElement]
..... //depends on how your xml looks like

NSXMLParser problem with "&"(Ampersand) character

My NSXMLParsing is not working because of "&" character.. my code s below .any help please ?
NSString *myRequestString = [NSString stringWithFormat:#"http://abc.com/def/webservices/aa.php?family_id=%d",self.passFamilyId];
//NSLog(#"Requested Service = %#",myRequestString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:myRequestString]];
[request setHTTPMethod: #"POST" ];
NSData *downloadedData = [ NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
//NSLog (#"string is :%#" ,str);
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
// Call the XMLParsers's initXMLParse method.
ClientDetailXmlParser *parser = (ClientDetailXmlParser*)[[ClientDetailXmlParser alloc] initXMLParser];
[xmlParser setDelegate:parser];
BOOL success = [xmlParser parse];
// Check for XML parsing.
if(success)
{
NSLog(#"No Errors in clientDetailXml.xml");
}
else
{
NSLog(#"Error Error Error in clientDetailXml.xml!!!");
}
[parser release];
parser = nil;
if (objClientAddUpdate != nil) {
[objClientAddUpdate createBubbleList];
}
Replace
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
With:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[contentString dataUsingEncoding:NSUTF8StringEncoding];
Very similar to sepehr-mahmoudian's answer, but instead of replace any & you should really just replace & characters that are unescaped, to do this you can use a regexp:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
//NSString *contentString = [str stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSData * data=[str dataUsingEncoding:NSUTF8StringEncoding];
With:
NSString *str = [[NSString alloc] initWithData:downloadedData encoding:NSASCIIStringEncoding];
NSRange searchedRange = NSMakeRange(0, [str length]);
NSString *pattern = #"&(?!(#[0-9]{2,4}|[A-z]{2,6});)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
str = [regex stringByReplacingMatchesInString:str options:0 range:searchedRange withTemplate:#"&"];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
Here's what worked for me:
NSString *response = [[NSString alloc]initWithData:dataResponse encoding:NSUTF8StringEncoding];
NSString *newResponse = [response stringByReplacingOccurrencesOfString:#"&amp:" withString:#"AND"];
NSData *dataObj = [newResponse dataUsingEncoding:NSUTF8StringEncoding];
If I replaced it with symbol '&', the response would be correct, but it would throw parsing error: 68. So I had to use 'and'.

NSMutableURLRequest setHTTPBody

i took this code from a different question and my script file has more inputs, not just mydata, also the data going into the mydata should not be static text, it should be from a NSString.
So my question is, how do i post multiple pieces of data to my script and how would I input a value from a NSString because my understand is i cannot use NSStrings with c data types. not sure if thats the correct terminology so please correct me if i am wrong.
const char *bytes = "mydata=Hello%20World";
NSURL *url = [NSURL URLWithString:#"http://www.mywebsite.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseString = [[NSString alloc] initWithFormat:#"%#", responseData];
NSLog(#"responseData: %#", responseData);
userData = responseData;
New issue using answer below
NSMutableData *data = [NSMutableData data];
NSString *number = numberIB.text;
NSString *name = nameIB.text;
NSString *nameString = [[NSString alloc] initWithFormat:#"name=", name];
NSString *numberString = [[NSString alloc] initWithFormat:#"number=", number];
NSLog(nameString);
NSLog(numberString);
[data appendData:[nameString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[numberString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.siteaddress.com/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//[request setHTTPBody:[NSData dataWithBytes:data length:strlen(data)]];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseString = [[NSString alloc] initWithFormat:#"%#", responseData];
NSLog(#"responseData: %#", responseData);
the NSLogs for nameString and numberString come back name= and number= without any data. causing no data to be sent to my script.
You can use an NSMutableData object to append bytes as needed, like so:
NSMutableData *data = [NSMutableData data];
const char *bytes = "mydata=Hello%20World";
[data appendBytes:bytes length:strlen(bytes)];
//...
const char *moreBytes = "&someMoreData=Fantastic";
[data appendBytes:moreBytes length:strlen(moreBytes)];
Edit: If you want to append a NSString into the data buffer, you can use -[NSString dataUsingEncoding:] and pass it off to -appendData:
NSString *someString = #"blah";
[data appendData:[someString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:data];

JSON parsing error

I am trying to parse some JSON. I've passed a constant key value and a string - butI'm receivng 16 objects in the statuses array and 20 objects in ststuses1.
Are any of the parsing steps wrong?
I have included the code for the JSON parser.
Thanks in advance.
SBJSON *parser = [[SBJSON alloc] init];
NSString *urlString =[NSString stringWithFormat:#"http://api.shiki.com/api/serch?key=%#&q=%#",apiKey, string];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSMutableArray *statuses = nil;
statuses = [[NSMutableArray alloc]init];
statuses = [parser objectWithString:json_string error:nil];
NSMutableArray *statuses0 = [[statuses valueForKey:#"offers"] valueForKey:#"offer"];
NSLog(#"Array Contents: %#", statuses0);
I guess that's not the only syntax-error in your code...
Please define statuses and ststuses1. I can only see statuses (redefined 2 times) and statuses0. Also please post a sample of the json-data you're parsing so I can take a look at it.