Parse CSV file in Objective C


Sometimes we have a bulk of data in a .csv file which we need to add or access in our iOS Application.
For this we can add that .csv file in application's bundle, fetch data from it and store it in an NSArray for use.

Follow the steps:

1. Once list of Country Names so i downloaded the full-country-list.csv from internet and added it in my application's bundle by simply dragging it.
2. Now i just located that file path and stored in 'strPath' variable, then stored its contents and encoding type in 'strFile' variable.
3. Checked if file is present and i am able to read it.
4. Now i allocated & initialized an NSArray object 'arrayCountry'.
5. To parse file use 'strFile componentsSeparatedByString:@"\n"' and store it in arrayCountry. This .csv file is seperated with new line character, if .csv is seperated by comma use ',' instead of '\n'.
6. And we are done with parsing .csv file and we have all country names in arrayCountry NSArray object.


    NSString *strPath = [[NSBundle mainBundle] pathForResource:@"full-country-list" ofType:@"csv"];
    NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
    if (!strFile) {
        NSLog(@"Error reading file.");
    }
    NSArray *arrayCountry = [[NSArray alloc] init];
    arrayCountry = [strFile componentsSeparatedByString:@"\n"];
    
    for(NSString *countryname in arrayCountry) {
        NSLog(@"%@", countryname);
        
    }
    NSLog(@"Countries Count: %i", [arrayCountry count]);

Code: Download

Comments

Popular posts from this blog

UITableView - Add or Remove Rows Dynamically (Objective C & Swift Source codes)

payUmoney Payment Gateway Integration in iOS App (Objective C)

Check Internet Connectivity Using AFNetworking 2.0