从NSURLResponse检测NSStringEncoding的功能? [英] Function to detect the NSStringEncoding from NSURLResponse?
问题描述
我只是想知道是否有任何现有的类别或任何类型的函数会从NSURLResponse对象返回NSStringEncoding常量。
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 .
我目前面临的问题是,当我将Web服务响应数据转换为String时,我将编码硬编码为NSUTF8StringEncoding,然后它实际上会导致问题,如我的网络服务有时会返回以UTF8编码的响应,有时以ASCII编码(我对所有编码都不太确定,但有时在响应中有其他语言字符,如日语,中文等)
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 )
所以我的想法是在NSURLResponse上有一个类别来检测编码并返回
例如。
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];
推荐答案
还有更好的方法。
您可以将URLResponse中的编码名称作为字符串,然后搜索相应的NSStringEncoding。
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));
此外 encodingName
可能是零,如果有的话对于提供的 encodingName
, encodingType
变量的结果值无效。
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.
这篇关于从NSURLResponse检测NSStringEncoding的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!