Create a Custom Formatted Dictionary Array from CSV File of Data - ios

I've created an iPhone app that has a dictionary array of locations (lat,long,point). I created the array by manually entering each value.
myLocationArray = #[
#{
kStation : #"1",
kLatitude : #( 41.656467),
kLongitude : #(-81.277963)
},
#{
kStation : #"2",
kLatitude : #(41.657118),
kLongitude : #(-81.276545)
},
#{
kStation : #"3",
kLatitude : #(41.658493),
kLongitude : #(-81.273542)
},
...
This is good and works but now I want to create this array programmatically by getting the data from a .CSV file. I have a .CSV file (TestCSV.csv) that looks like this.
41.656467,-81.277963,27200
41.657118,-81.276545,27650
41.658493,-81.273542,28631.5
41.660728,-81.268547,30195
41.661830,-81.266065,30991
41.662828,-81.263819,31700
41.663677,-81.261962,32300
41.664578,-81.259909,32950
41.666210,-81.256312,34100
41.666921,-81.254708,34605
41.668043,-81.252191,35400
41.669044,-81.250043,36099
41.670120,-81.247495,36900
41.670778,-81.245957,37380
41.671459,-81.244292,37905
41.672028,-81.242832,38349
41.672487,-81.241702,38700
41.673106,-81.240175,39175
41.674364,-81.237007,40150
41.675170,-81.235038,40762.5
41.675716,-81.233698,41182
41.676143,-81.232614,41516
Specifically, I'd like to create myLocationArray (with formatting as shown) by reading straight from the TestCSV.csv. I'm not familiar with the code to achieve this and would really appreciate some direction.
Also, would it be any different or easier if the data was provided via text file instead of csv?

Try
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Locations" ofType:#"csv"];
NSString *csvString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *locations = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *locationsArray = [NSMutableArray array];
for (NSString * location in locations)
{
NSArray *components = [location componentsSeparatedByString:#","];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
NSString *station = components[2];
NSDictionary *dict = #{#"kLatitude": #(latitude),
#"kLongitude": #(longitude),
#"kStation": station};
[locationsArray addObject:dict];
}
CSV File
Answer inspired from

csv file IS a plain-text file. To achive what you want you can use NSScanner and NSString componentsSeparatedByString: Everything else is really simple.

Answer provided by Anupdas. Cheers!
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Locations" ofType:#"csv"];
NSString *csvString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *locations = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *locationsArray = [NSMutableArray array];
for (NSString * location in locations)
{
NSArray *components = [location componentsSeparatedByString:#","];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
NSString *station = components[2];
NSDictionary *dict = #{#"kLatitude": #(latitude),
#"kLongitude": #(longitude),
#"kStation": station};
[locationsArray addObject:dict];
}

Related

Put multiple arrays in Dictionary

I am parsing a CSV file multiple times with for loop, here I need to store these arrays one by one dictionary. There are very less questions in stack about adding NSArray to NSDictionary. I am parsing CSV with below code but I strucked at storing in NSDictionary, The program is terminating and showing warning at assigning string to dictionary
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serail No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: keysArray forKeys: string];
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSString *key = [NSString stringWithFormat:#"serial%d",i];
[dict setObject:keysArray forKey:key];
}
To get back data from dictionary,
NSArray *array = [dict valueForKey:#"serial24"];//to get array 24.
If I understand you correctly, you want to add the arrays to a dictionary, with the key being the string value of integer i ? What you need to do is allocate the dictionary outside your loop -
NSMutableDictionary *dict=[NSMutableDictionary new];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serial No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
dict[string]=keysArray;
}
I am not sure why you would want to do this, because this is basically an array. You could simply do -
NSMutableArray *outputArray=[NSMutableArray new];
for (NSString *keysString in csvArray) {
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
[outputArray addObject:keysArray];
}

Fetch Substring from NSString

I have the following string :
Item 1#Item 2#Item 3#Item 4#Item 5#Item 6#Item 7#Item 8#Item 9#Item 10#Item 11#Item 12#Item 13#Item 14#Item 15#
I want to extract each Item name. How can it be done?
try this
NSString *temp = #"Item 1#Item 2#Item 3#Item 4#Item 5#Item 6#Item 7#Item 8#Item 9#Item 10#Item 11#Item 12#Item 13#Item 14#Item 15#";
NSArray *arr = [temp componentsSeparatedByString:#" "];
NSLog(#"%#", arr);
Separate each string
NSString *str = #"Item 1#Item 2#Item 3#Item 4#Item 5#Item 6#Item 7#Item 8#Item 9#Item 10#Item 11#Item 12#Item 13#Item 14#Item 15#";
NSArray *components = [str componentsSeparatedByString:#"#"];
NSString *string=#"Item 1#Item 2#Item 3#Item 4#Item 5#Item 6#Item 7#Item 8#Item 9#Item 10#Item 11#Item 12#Item 13#Item 14#Item 15#";
NSArray *array=[[NSArray alloc] initWithObjects:[string componentsSeparatedByString:#"#"]];

Fetching data from SQLite and want to get only the last value of column id

I am fetching data from SQLite and want to get only the last value of column id in XCode.The code is
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSString *valvar;
valvar = [_uid lastObject];
NSNumber *custval = [_uid valueForKey: #"#lastObject"];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",custval,"1"];
NSLog(#"%#", imgval1);
Please tell me how can I get only the value because by using the above code I am getting array with last value of id.
I think this your case, try this it maybe help you
NSArray *temp=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
// NSString *tmmp=[temp0ne lastObject];
NSArray *finalStr=[uid lastObject];
NSLog(#"Dictionary is---->%#",[finalStr lastObject]);
Output:
3_1
EDIT
NSArray *temp=[NSArray arrayWithObjects:#"(1)",#"(2)",#"(3)", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
NSString *tmmp=[temp0ne lastObject];
NSString *final=[tmmp stringByReplacingOccurrencesOfString:#"(" withString:#""];
final=[final stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",final,"1"];
NSLog(#"%#", imgval1);
I don't know is this correct way or not try this....otherwise have look this link
I don't fully understand your code structure hehe. Try this:
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSNumber *custval = [_uid objectAtIndex:[_uid count]-1];
*
NSString *str = [NSString stringWithFormat#"%#",custval];
str = [str stringByReplacingOccurrencesOfString:#"("
withString:#""];
NSString *finalCustval = [NSString stringWithFormat#"%#",str];
finalCustval = [finalCustval stringByReplacingOccurrencesOfString:#")"
withString:#""];
*
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",finalCustval ,"1"];
NSLog(#"%#", imgval1);
UPDATE
try adding the ones with *.

IOS: How to read specific data in one list of XML

When I use NSXMLParser to parse XML in iPhone app, I know how to do it in the scenario like this:
> <title>L3178 : Freiensteinau Richtung Grebenhain</title> // From XML
But, if I want to extract data from a list, e.x. I want to get the lat and lon from <>id>, how should I deal with that?
<>id>
http://www.freiefahrt.info/?id=468B0243-E15C-4580-9AD2 14D8CF692999&lon=9.3495&lat=50.49465&country=DE&filter=0&expires=2013-12-20T03:13:00
<>/id>
It is very strange if I use instead of <>id>, it will disappear. So, I have to use this ugly notation.
Thank you in advance!
Create a method which extracts parameters from urlString
- (NSDictionary *)paramsFromURLString:(NSString *)urlString
{
NSRange range = [urlString rangeOfString:#"?"];
NSString *subString = [urlString substringFromIndex:range.location+range.length];
NSArray *components = [subString componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
for (NSString *string in components) {
NSRange subRange = [string rangeOfString:#"="];
NSString *key = [string substringToIndex:subRange.location];
NSString *value = [string substringFromIndex:subRange.location+subRange.length];
[params setObject:value forKey:key];
}
return params;
}
From the params find the lat and lon
NSString *urlString = #"http://www.freiefahrt.info/?id=468B0243-E15C-4580-9AD2 14D8CF692999&lon=9.3495&lat=50.49465&country=DE&filter=0&expires=2013-12-20T03:13:00";
NSDictionary *params = [self paramsFromURLString:urlString];
NSString *latitude = params[#"lat"];
NSString *longitude = params[#"lon"];

NSString substring processing

I have a string with the following value:
[{ProjLead=irshad, ProjName=irshad proj, ProjectId=365}]
I would like to get the value for ProjLead, ProjName and ProjectId separately. How can I do it?
You can combine some methods from NSString class.
Something like this:
NSString *string = #"[{ProjLead=irshad, ProjName=irshad proj, ProjectId=365}]";
NSString *parametersString = [string substringWithRange:NSMakeRange(2, string.length - 4)];
NSArray *parameters = [parametersString componentsSeparatedByString: #", "];
NSMutableArray *values = [NSMutableArray array];
for (NSString *parameter in parameters) {
[values addObject:[[parameter componentsSeparatedByString:#"="] objectAtIndex:1]];
}
values array is what you want.

Resources