iphone – 如何在Objective-C中从服务器下载CSV文件
发布时间:2020-12-15 01:47:06 所属栏目:百科 来源:网络整理
导读:我正在开发一个新的iPhone应用程序,在这里,我已经从本地解析了一个’csv’文件,并与我一起工作.当我尝试以编程方式从服务器下载’csv’文件时,它没有为我锻炼.你可以帮我吗? 从本地文件加载数据(工作正常) - (void)viewDidLoad{ [super viewDidLoad]; NSStr
我正在开发一个新的iPhone应用程序,在这里,我已经从本地解析了一个’csv’文件,并与我一起工作.当我尝试以编程方式从服务器下载’csv’文件时,它没有为我锻炼.你可以帮我吗?
从本地文件加载数据(工作正常) - (void)viewDidLoad { [super viewDidLoad]; NSString * file = [[NSBundle bundleForClass:[self class]] pathForResource:@"sample" ofType:@"csv"]; NSStringEncoding encoding = 0; NSString * csv = [NSString stringWithContentsOfFile:file usedEncoding:&encoding error:nil]; NSArray *fields = [csv CSVComponents]; NSLog(@"fields: %@",fields); //getting the result content } 从服务器下载文件(失败) -(void) connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); //nothing showing here NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0]; NSString *fullName = [NSString stringWithFormat:@"quotes.csv"]; NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@",docDir,fullName]; [receivedData writeToFile:fullFilePath atomically:YES]; } -(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"data: %@",data); //nothing showing here if (receivedData) [receivedData appendData:data]; else receivedData = [[NSMutableData alloc] initWithData:data]; } - (void)loadDatafromURL { NSURL *url = [NSURL URLWithString:@"http://download.finance.yahoo.com/d/quotes.csv?s=^GSPC,^IXIC,^dji,^GSPC,^BVSP,^GSPTSE,^FTSE,^GDAXI,^FCHI,^STOXX50E,^AEX,^IBEX,^SSMI,^N225,^AXJO,^HSI,^NSEI&f=sl1d1t1c1ohgv&e=.csv"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection connectionWithRequest:request delegate:self]; } 解决方法
实现此方法:
-(void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error 你会发现你得到的错误 Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xf663f40 {NSUnderlyingError=0xf663de0 "bad URL",NSLocalizedDescription=bad URL} 我之前考虑过以这种方式下载信息,我认为你遇到的一个问题是必须用“”分隔单独的符号.此外,在拉取索引时,您不能将“^”符号作为URL的一部分传递.你必须用“^”替换它. 所以,添加这个: - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"%@",[error description]); } 并将您的网址更改为: NSString *urlString = @"http://download.finance.yahoo.com/d/quotes.csv?s=^GSPC+^IXIC+^dji+^GSPC+^BVSP+^GSPTSE+^FTSE+^GDAXI+^FCHI+^STOXX50E+^AEX+^IBEX+^SSMI+^N225+^AXJO+^HSI+^NSEI&f=sl1d1t1c1ohgv&e=.csv"; NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]; 现在它适合我!我甚至检查了输出.csv文件,它看起来不错!每行一个完整的报价. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |