Function to detect the NSStringEncoding from NSURLResponse?

耗尽温柔 提交于 2019-12-01 07:32:39

问题


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

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!