简体   繁体   中英

How to convert CSV format into NSData or NSString in iPhone?

I am making an iPhone app which requires the current Stock Prices.

I am receiving the data in CSV format from a link given below.

http://finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk

Is it possible to convert the CSV format to NSData or NSString format? If yes, how can I do so?

What can be the other alternatives for this?

Don't re-invent the wheel: CHCSVParser is a native CSV parser written in Objective-C. It properly handles quoted fields, escaped characters, etc. It has convenience methods ( +[NSArray arrayWithContentsOfCSVFile:...] ) and chunks the file reading so as not to produce low memory warnings.

Here's (more or less) how you'd use it. That the CSV file is remote complicates things a little bit, but not much (you have to download the contents of the URL into a string, and then pass that string into the parser).

#import "CHCSV.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString * csv = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://download.finance.yahoo.com/d/quotes.csv?s=RHT+MSFT&f=sb2b3jk"]];
    NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:NSUTF8StringEncoding error:nil];
    //You can also do:  rows = [csv CSVComponents];
    NSLog(@"rows: %@", rows);
    [pool drain];
    return 0;
}

This logs:

2010-12-23 09:05:44.431 CHCSVParser[99377:a0f] (
        (
        RHT,
        "46.48",
        "46.46",
        "26.51",
        "49.00"
    ),
        (
        MSFT,
        "28.23",
        "28.22",
        "22.73",
        "31.58"
    ),
        (
        ""
    )
)

It returns an NSArray of NSArrays of NSStrings .

Assuming you are asking how to parse the CSV data, here's a very simple bit of code to do it. Use google if you want to find more advanced parsers - they're out there..

// CsvParser2.h
#import <Foundation/Foundation.h>

@interface NSString (CsvParser2)
// Returns an array of arrays for rows & columns
-(NSArray *)csvRows;
@end


// CsvParser2.m
#import "CsvParser2.h"

@implementation NSString (CsvParser2)

// Simplest possible implementation... NOT memory efficient!
// No apologies, no refunds...
-(NSArray *)csvRows
{   
    NSMutableArray* outRows = [NSMutableArray array];

    NSCharacterSet* newlineCharSet = [NSCharacterSet newlineCharacterSet];
    NSCharacterSet* separatorCharactersSet = [NSCharacterSet characterSetWithCharactersInString:@","];

    NSArray* lines = [self componentsSeparatedByCharactersInSet:newlineCharSet];
    for ( NSString* line in lines )
    {
        if ( !line.length ) continue;
        NSArray* columns = [line componentsSeparatedByCharactersInSet:separatorCharactersSet];
        if ( columns.count )
        {
            [outRows addObject:columns];
        }
    }

    return outRows; // autoreleased
}

@end

This is defined as a category on NSString, to use it just do

NSMutableArray* myResponseAsArrayOfArraysOfStrings = [myCsvResponseAsAString csvRows];
for ( NSArray* row in myResponseAsArrayOfArraysOfStrings )
{
   for ( NSString* column in row )
   {
       NSLog( "%@", column );
   }
}

Hope this helps!

NOTE, this parser doesn't deal with quotes. Namely 1. If a field is quoted, the quotes are not stripped off. 2. If the quoted portion contains a comma the parser will split the line incorrectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM