来自 URL 下载的不同 NSString 结果 [英] Different NSString results from URL download
问题描述
我正在解析从网站获取的字符串,但根据我的下载方式得到不同的结果.它是这样工作的:
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];
按照以下方式行不通.我首先下载数据,将其输入 NSMutableData *articleData
,然后使用 initWithData:encoding:
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;
}
似乎两个版本的结果 NSString *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.
推荐答案
实现委托方法 connectionDidFinishLoading 以确保连接加载已完成,您可以在此处调用数据方法.也尝试使用 NSASCIIStringEncoding 而不是NSSymbolStringEncoding.
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
}
这篇关于来自 URL 下载的不同 NSString 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!