Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of NSData to NSString fails due to some charecters

I am converting NSData to NSString which I got as response of a url using the following method.

NSString *result = [[NSString alloc] initWithData:_Data encoding:NSUTF8StringEncoding];

It works fine and I am using this for a long time but today I faced an issue while loading the data (paging) at one page my result gives null string.

So I searched SO and found a method from this link NSData to NSString converstion problem!

[NSString stringWithCString:[theData bytes] length:[theData length]];

and this works fine.

My queries,

  1. The method was deprecated in iOS 2.0. If I use this will I be facing any issue in future?
  2. I think this is the text that made the method fail enter image description here What is this and is there any way that I can encode this using NSUTF8StringEncoding?
  3. What is the the alternative encoding that I can use for encoding all the type of characters like in the above pic?
like image 657
vamsi575kg Avatar asked Dec 21 '25 10:12

vamsi575kg


1 Answers

In order to obtain the type of the content which is sent by the server, you need to inspect the Content-Type header of the response.

The content type's value specifies a "MIMI type", e.g.:

Content-Type: text/plain

A Content-Type's value may additionally specify a character encoding, e.g.:

Content-Type: text/plain; charset=utf-8

Each MIME type should define a "default" charset, which is to be used when there is no charset parameter specified.

For text/* media types the default charset is US-ASCII. (see RFC 6657, §3).

The following code snippet demonstrates how to safely encode the body of a response:

    - (NSString*) bodyString {
        CFStringEncoding cfEncoding = NSASCIIStringEncoding;
        NSString* textEncodingName = self.response.textEncodingName;
        if (textEncodingName) {
            cfEncoding = CFStringConvertIANACharSetNameToEncoding( (__bridge CFStringRef)(textEncodingName) );
        }
        if (cfEncoding != kCFStringEncodingInvalidId) {
            NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
            return [[NSString alloc] initWithData:self.body encoding:encoding];
        }        
        else {
            return [self.body description];
        }
    }

Note:

body is a property returning a NSData object representing the response data.

response is a property returning the NSHTTPURLResponse object.

like image 83
CouchDeveloper Avatar answered Dec 23 '25 01:12

CouchDeveloper