异步相当于 NSString 的 -initWithContentsOfURL:usedEncoding:error:
NSString
的 initWithContentsOfURL:usedEncoding:error:
方法会自动检测正确的字符串编码,以解码指定 URL 中的数据。但是,此方法是同步的,我尝试使用 NSURLConnection 异步执行相同的任务。
我遇到的问题是,当我从 URL 获取 NSData 时,没有方法可以在不知道编码的情况下轻松将该数据转换为 NSString 。当我提取 HTML 文档时,URL 可以是互联网上的任何网站,编码可以是各种各样的东西。
有没有一种方法可以发现编码,基本上完全执行 initWithContentsOfURL:usedEncoding:error:
所做的事情?
NSString
's initWithContentsOfURL:usedEncoding:error:
method will automatically detect the correct string encoding to decode the data from the specified URL. However, this method is synchronous, and I am trying to perform the same task asynchronously using an NSURLConnection
.
The problem I'm having is that when I get the NSData
from the URL, there's no method to easily convert that data into an NSString
without knowing the encoding. As I'm pulling in HTML documents the URLs could be any website on the internet, and the encodings will be all sorts of things.
Is there a way of discovering the encoding, to basically perform exactly what initWithContentsOfURL:usedEncoding:error:
does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是您的
connection:didReceiveResponse:
委托方法的样子:另外,我建议您阅读 2010-02-19 星期五问答:字符编码,作者:Mike Ash。
Here is how your
connection:didReceiveResponse:
delegate method would look like:Also, I suggest you to read Friday Q&A 2010-02-19: Character Encodings by Mike Ash.
如果您正在为桌面编程,您可以链接到核心服务并使用文本编码转换管理器提供的嗅探器;请参阅
TECCreateSniffer()
和随附的函数。如果您的目标是 iOS,则必须异步加载数据,将其异步写入文件,然后同步使用您提到的 NSString 方法,或者尝试使用任何启发式方法自行嗅探编码你可以制作或掠夺。
If you are programming for the desktop, you can link in Core Services and use the sniffer provided by the Text Encoding Conversion Manager; see
TECCreateSniffer()
and accompanying functions.If you are targeting iOS, you will either have to load the data asynchronously, write it to a file asynchronously, and then synchronously use the
NSString
method you mentioned, or attempt to sniff the encoding yourself using any heuristic you can craft or pillage.