NSString *urlStr = [[NSString alloc] initWithFormat:@"http://www.somewhere.com/LunchSpecials.csv"];
NSURL *lunchFileURL = [NSURL URLWithString:urlStr];
NSStringEncoding encoding = 0;
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVFile:[lunchFileURL path] usedEncoding:&encoding error:nil];
[p setParserDelegate:self];
[p parse];
[p release];
感谢有人能给我的任何帮助。
答案 0 :(得分:6)
-[NSURL path]
没有做你期望的事。
如果我有网址http://stackoverflow.com/questions/4636428
,则-path
为/questions/4636428
。当您将该路径传递给CHCSVParser时,它将尝试在本地系统上打开该路径。由于该文件不存在,您将无法打开它。
您需要做什么(正如Walter指出的那样)是在本地下载CSV文件,然后打开它。您可以通过多种不同方式下载文件(+[NSString stringWithContentsOfURL:...]
,NSURLConnection
等)。一旦您将文件本地保存到磁盘或内存中的CSV字符串,您就可以将其传递给解析器。
如果这是一个非常大的文件,那么您需要alloc
/ init
一个CHCSVParser
,其中包含CSV文件本地副本的路径。然后,解析器将逐位读取它,并通过委托回调告诉您它找到了什么。
如果CSV文件不是很大,那么你可以这样做:
NSString * csv = ...; //the NSString containing the contents of the CSV file
NSArray * rows = [csv CSVComponents];
这将返回NSArray
NSArrays
NSStrings
的{{1}}。
与此类似,最后一种方法是使用NSArray
类别方法:
NSString * csv = ...;
NSError * error = nil;
NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:[csv fastestEncoding] error:&error];
这将返回相同的结构(NSArray
NSArrays
的{{1}},但如果遇到语法错误,它还会为您提供NSStrings
个对象在CSV文件中(即格式错误的CSV)。
答案 1 :(得分:1)
我认为你需要一个NSString,而不是NSURL对象传递给解析器,所以你将NSString更改为NSURL所做的额外部分就是问题所在。查看CHCSVParser文档,看起来他想在init中使用NSString。
所以也许你可以这样做:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *lunchFileURL = [[NSString stringWithFormat:@"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL] encoding:NSUTF8StringEncoding error:&err];
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVString:lunchFile usedEncoding:&encoding error:nil];