Different NSString results from URL download

纵饮孤独 提交于 2019-12-23 04:21:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!