问题
I am parsing a string that I obtain from a website but get different results depending on how I download. This way it works:
NSString *tagiString = @"http://tagesanzeiger.ch";
NSURL *tagiURL = [NSURL URLWithString:tagiString];
NSError *error;
NSString *text =[NSString stringWithContentsOfURL:tagiURL
encoding:NSASCIIStringEncoding
error:&error];
Te following way it does not work. I first download the data, feed it into the NSMutableData *articleData and then convert to a NSString with initWithData:encoding:
- (void)downloadWebsite
{
NSString *tagiString = @"http://tagesanzeiger.ch";
NSURL *websiteURL = [NSURL URLWithString:tagiString];
NSURLRequest *request = [NSURLRequest requestWithURL:websiteURL];
connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
[articleData appendData:data];
}
- (NSString *)data
{
NSString *text = [[NSString alloc] initWithData:articleData
encoding:NSSymbolStringEncoding];
return text;
}
Seems like the resulting NSString *text content is not the same for both versions? Do I need to use a different string encoding? I have tried many without success.
回答1:
Implement the delegate method connectionDidFinishLoading to ensure the connection loading has finished where you can call your data method. Also try to use NSASCIIStringEncoding instead of NSSymbolStringEncoding.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *text = [[NSString alloc] initWithData:self.articleData
encoding:NSASCIIStringEncoding];
//do whatever you need to do with the text
}
回答2:
Yes, you need to use a different string encoding. You can try NSUTF8StringEncoding. Here it's working for me. And utf-8 is almost the most popular encoding way.
来源:https://stackoverflow.com/questions/16880686/different-nsstring-results-from-url-download