dcprog dcprog - 1 year ago 89
iOS Question

How to read the first column data from CSV file and compare it with user input?

I am developing an app where users can upload a csv file to documents folder of app (I finished it). But I want to give a textfield to users in the app and ask them to enter a id number and this number will be checked with the uploaded csv files first column. If it matches then display an alert saying that its found a match or else it doesn't.

Answer Source

I believe csv files are text files with comma separated columns and newline (\n) separated rows. So one way to search every row's first column element would be to use NSString's method componentsSeparatedByString:.

EDIT: Load csv file into NSString instance.

NSString * pstrCSVFilePath= [[NSBundle mainBundle] pathForResource:@"CSVFile" ofType:@""]
NSString * pstrCSVFile= [NSString stringWithContentsOfFile:pstrCSVFilePath encoding:NSASCIIStringEncoding error:NULL];

NSArray * paRowsOfCSVFile= [pstrCSVFile componentsSeparatedByString:@"\n"];
NSArray * paColumnsOfRow;
NSString * pstrFirstColumn;
for(NSString * pstrRow in paRowsOfCSVFile)
    paColumnsOfRow= [pstrRow componentsSeparatedByString:@","];
    pstrFirstColumn= [paColumnsOfRow objectAtIndex:0];
    if([pstrFirstColumn localizedCaseInsensitiveCompare:myTextField.text] == NSOrderedSame)
         //Found the search string in the CSV file. 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download