Download remote csv to CHCSVParser

Hey guys. I am using Dave DeLong CHCSVParser to analyze csv. I can parse csv locally, but I cannot download its remote csv file. I have been looking at my MacBook for too long, and the answer is right in front of me. Here is my code:

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];

Thanks for any help anyone can give me.

+3
source share
2 answers

-[NSURL path] does not fulfill what you expect.

If I have a URL http://stackoverflow.com/questions/4636428, then it -pathis equal /questions/4636428. When you pass this path to CHCSVParser, it will try to open this path on the local system. Since this file does not exist, you cannot open it.

( ), CSV , . (+[NSString stringWithContentsOfURL:...], NSURLConnection ..). , , , CSV , .

, alloc/init a CHCSVParser CSV. , , .

CSV , :

NSString * csv = ...; //the NSString containing the contents of the CSV file
NSArray * rows = [csv CSVComponents];

NSArray NSArrays NSStrings.

NSArray:

NSString * csv = ...;
NSError * error = nil;
NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:[csv fastestEncoding] error:&error];

(NSArray of NSArrays of NSStrings), NSError, ​​ CSV (.. CSV).

+6

, NSString, NSURL , , NSString NSURL, . CHCSVParser, , NSString init.

, , - :

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];
+1

Source: https://habr.com/ru/post/1784305/


All Articles