darshan
darshan

Reputation: 1115

Convert Unicode character to NSString

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"

Upvotes: 4

Views: 20927

Answers (3)

Piyush
Piyush

Reputation: 16

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" 

Upvotes: 0

sElanthiraiyan
sElanthiraiyan

Reputation: 6268

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.

Upvotes: 7

Prabhjot Singh Gogana
Prabhjot Singh Gogana

Reputation: 1408

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];

Upvotes: 2

Related Questions