I just wanted to know if there is any existing category or any sort of function that will return me NSStringEncoding constant out of NSURLResponse object .
The issue I am facing at the moment is as I have hardcoded the encoding to NSUTF8StringEncoding when I convert the web service response data to String then it actually causes an issue , as my web service sometimes returns the response encoded in UTF8 and sometimes encoded in ASCII ( well I am not too sure about all the encodings though but yes there are sometimes other languages characters in the response like Japanese , Chinese etc )
So My idea is to have a category on NSURLResponse that detects the encoding and returns eg .
NSURLResponse * response = // NSURLResponse object ( web service response headers )
NSData * responseData = // NSData object ( web service response data )
NSStringEncoding encoding = [response stringEncodingUsed];
NSString * responseText = [[NSString alloc]initWithData:responseData encoding:encoding];
There is a better way.
You can get the encoding name from URLResponse as a string, then search for the appropriate NSStringEncoding.
NSString *encodingName = [aURLResponse textEncodingName];
NSStringEncoding encodingType = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)encodingName));
Also encodingName
might be nil and if there is no appropriate result for the provided encodingName
the result value for the encodingType
variable will not be valid.
来源:https://stackoverflow.com/questions/17836111/function-to-detect-the-nsstringencoding-from-nsurlresponse