Load remote csv into CHCSVParser

前端 未结 2 1414
灰色年华
灰色年华 2021-01-14 13:36

I am using Dave DeLong\'s CHCSVParser to parse a csv. I can parse the csv locally, but I cannot get it load a remote csv file. I have been staring at my MacBook way too long

相关标签:
2条回答
  • 2021-01-14 13:56

    -[NSURL path] is not doing what you're expecting.

    If I have the URL http://stackoverflow.com/questions/4636428, then it's -path is /questions/4636428. When you pass that path to CHCSVParser, it's going to try and open that path on the local system. Since that file doesn't exist, you won't be able to open it.

    What you need to do (as Walter points out) is download the CSV file locally, and then open it. You can download the file in several different ways (+[NSString stringWithContentsOfURL:...], NSURLConnection, etc). Once you've got either the file saved locally to disk or the string of CSV in memory, you can then pass it to the parser.

    If this is a very big file, then you'll want to alloc/init a CHCSVParser with the path to the local copy of the CSV file. The parser will then read through it bit by bit and tell you what it finds via the delegate callbacks.

    If the CSV file isn't very big, then you can do:

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

    That will return an NSArray of NSArrays of NSStrings.

    Similar to this last approach is using the NSArray category method:

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

    This will return the same structure (an NSArray of NSArrays of NSStrings), but it will also provide you with an NSError object if it encounters a syntax error in the CSV file (ie, malformed CSV).

    0 讨论(0)
  • 2021-01-14 14:16

    I think you need an NSString, not an NSURL object to pass to the parser so the extra part you are doing with changing the NSString to an NSURL is the issue. Looking at the CHCSVParser documentation, it looks like he wants NSString in the init.

    So maybe you could do something like:

    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];
    
    0 讨论(0)
提交回复
热议问题