Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

iphone - How to use stringWithContentsOfURL: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];

I get a empty my_string variable.

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.

What's wrong ?

Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...