如何使用stringWithContentsOfURL:encoding:error :? [英] How to use stringWithContentsOfURL:encoding:error:?

查看:476
本文介绍了如何使用stringWithContentsOfURL:encoding:error :?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用initWithContentsOfURL:encoding:error:像这样:

I am trying to use initWithContentsOfURL:encoding:error: like this :


NSURL *url = [[NSURL alloc] initWithString:@"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];

我得到一个空my_string变量。

I get a empty my_string variable.

我试过initWithContentsOfURL:方法(在iOS 2.0中已弃用),我得到我的页面的内容。但是我仍然需要指定编码语言。

I tried the initWithContentsOfURL: method (which is deprecated in iOS 2.0) and I get the content of my page. But I still need to specify a encoding language.

出现了什么问题?


推荐答案

您的文件的编码可能不是UTF8。

the encoding of your file is probably not UTF8.

如果您不知道文件的编码,可以尝试此方法:

If you don't know the encoding of your file, you could try this method:

- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error






您必须传递一个指向NSStringEncoding的指针,就像您对错误所做的那样。


you have to pass a pointer to a NSStringEncoding, like you did with error.:

NSURL *url = [[NSURL alloc] initWithString:@"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSStringEncoding encoding;
//NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
//                                                     encoding:NSUTF8StringEncoding
//                                                        error:&error];
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
                                                 usedEncoding:&encoding 
                                                        error:&error];

之后,您的编码就会出现在编码变量中。如果你对使用的编码不感兴趣,我想你也可以传递NULL作为指针。

after this your encoding is present in the encoding variable. If you are not interested in the used encoding, I guess you could pass NULL as pointer as well.

这篇关于如何使用stringWithContentsOfURL:encoding:error :?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆