Using NScanner to parse CSV File to Dictionary Array [duplicate] - ios

This question already has answers here:
Create a Custom Formatted Dictionary Array from CSV File of Data
(3 answers)
Closed 9 years ago.
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
I'd like to create myLocationArray (with formatting as shown) by parsing TestCSV.csv using NScanner. I've set up to parse the my data file.
NSString *pathToFile =[[NSBundle mainBundle] pathForResource:#"TestCSV" ofType: #"csv"];
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
if (!fileString) {
NSLog(#"Error reading file.");
}
NSScanner *scanner = [NSScanner scannerWithString:fileString];
I need help from here though. I've looked at many examples but it seems like this is where I need some code custom to my application. Thanks in advance for your time.

I don't understand why you're bothering with a scanner at all, seeing as your structure is so simple and predictable. Start with an empty NSMutableArray. You can split the file into lines like this:
NSArray *lines = [input componentsSeparatedByString:#"\n"];
Now enumerate that array. For each line, you can split the line at the commas:
NSArray *nums = [oneLine componentsSeparatedByString:#","];
The array nums is an array of three NSString values. For the first two items of the array, convert them to doubles with doubleValue and wrap that in an NSNumber. Make the NSDictionary for that line and add it to the NSMutableArray.

Don't try to re-invent the wheel, as there are a couple of pitfalls in the CSV file format (which is not even especially well defined).
There are for instance the special cases of newlines and commas within a field. Any algorithm based on just splitting by lines and commas is going produce incorrect results given such input. Also notice that Excel doesn't always use a comma as a separator, depending on the locale.
Use a library like CHCSVParser, which will cover those pitfalls.

Related

How to remove those characters in a string which are also present in an String array?

I have a long list of Array strings (Like 500 +). I want to use this array as my character set and remove the occurrences of these substrings in my String array in the Main string.
NSArray *Arr = #["a1","a2","a3" ..........];
NSString *mainString = #"Stackoverflow is a1Right Placa2e toa3 ask a4 for Help";
Expected Answer : StackOverflow is the best place to ask for help
It is something like this and I have to remove a1, a2, a3 and a4 from my Main String.
I have checked some methods like componentsSeparatedByCharactersInSet and Defining Character Array but none of them actually helped me to understand how to implement in Objective C.
A basic way to do this is mentioned below.
NSArray *Arr = #[#"a1",#"a2",#"a3",#"a4"];
NSString *mainString = #"Stackoverflow is a1Right Placa2e toa3 ask a4 for Help";
for (NSString* aValue in Arr) {
mainString = [mainString stringByReplacingOccurrencesOfString:aValue withString:#""];
}
NSLog(#"%#", mainString);
Hope this helps.

Concatenate Strings for Dictionary:syntax error

The following code to conditionally concatenate strings for a dictionary seems to work up to the point where I try to place the concatenated result in the dictionary. Can anyone see the error?
NSDictionary *jsonDictionary;
NSString* dictString = #"#\"first\":first,#\"last"
NSString *dictString2=dictString;
if (date.length>0&&![date isKindOfClass:[NSNull class]]) {
//only include this key value pair if the value is not missing
dictString2 = [NSString stringWithFormat:#"%#%s", dictString, "#\"date\":date"];
}
jsonDictionary = #{dictString2}; //syntax error. Says expected colon but that does not fix anything
The syntax for creating an NSDictionary using object literals is:
dictionary = #{key:value}
(and optionally, it can contain multiple key/value pairs separated by commas, but never mind that right now.)
Where "key" and "value" are both NSObjects.
Your line that is throwing the error only contains 1 thing. The contents of a the string in dictString2 has nothing to do with it.
It looks to me like you are trying to build a JSON string manually. Don't do that. Use NSJSONSerialization. That class has a method dataWithJSONObject that takes an NSObject as input and returns NSData containing the JSON string. That's how you should be creating JSON output.
Creating an NSDictionary with values that may be null:
NSDictionary *dict = #{
#"key" : value ?: [NSNull null],
};
When serializing a dictionary, NSNulls are translated to null in the JSON.
If you want to exclude such keys completely, instead of having them with a null value, you'll have to do more work. The simplest is to use an NSMutableDictionary and test each value before adding it.

Handling QR Code in ios

I am working on QR Codes where where i will get some contents with multiple fields (ex. name,address,contact number etc) from QR Code.
When I tried I am getting response.
But in single string format.
So if I want to separate these contents.
How do I can separate the contents in different fields.
response :
VERSION:3.0
N:Patil;Pradumna
FN:Pradumna Patil
ORG:techsanskar
TITLE:iphone
ADR:;;;;;;
TEL;WORK;VOICE:
TEL;CELL:9420256819
TEL;FAX:
EMAIL;WORK;INTERNET:
URL:
BDAY:
END:VCARD
Thank you.
If you have string in this format name,address,contact number
Like these are seperated by ',' You can use
NSArray *items = [theString componentsSeparatedByString:#","];
NSString *name = items[0];
NSString *address = items[1];//etc

How to convert a list to NSArray?

I keep getting this list which is stored as NSString:
(
"one",
two,
"three",
4
)
How do I convert the values into NSArray?
If you provide more information about where this list comes from or how it's made, maybe i can be of more help.
Otherwise, you can convert your string in an array of strings by "splitting" when the , appears, like so :
Your initial string is saved as myString
You should first remove then ( & ) at the start and the end of your string, and then do this :
NSArray* foo = [myString componentsSeparatedByString:#","];
And foo now contains these values :
"one"
two
"three"
4
But I still think you should give a little more information as i said at the start of this answer, because I have a feeling this is not exactly what you're looking for.
EDIT : as I said in comments, because it's a JSON, simply get the results into a dictionary, and then do :
NSArray *array = [results objectForKey:#"blocks"];
If your JSON is in this form, convert your JSON response in a dictionary and simply get the value of keyword "blocks" in an array. For example if you have
NSDictionary *dict = {"blocks": ["one", two, "three",4]};
The following will be your array
NSArray *array = [dict valueForKey:#"blocks"];

remove parentheses from JSON string

After extracting a string from JSON response:
NSString *responseMessage = [NSString stringWithFormat:#"%#",[[JSON objectForKey:#"Response"]valueForKey:#"Message"]];
NSLog(#"<%#>",responseMessage);
It looks like this:
<(
"not found"
)>
This is the relevant code:
So when I try to compare it, isEqualToString returns always false
([responseMessage isEqualToString:#"not found"])?NSLog(#"They are equal"):NSLog(#"They are different");//they are different
How to get rid of these parentheses to better compare the two strings? Thanx in advance.
It looks like you have an array here (which in Objective-C will print as a list with parentheses).
What is the source JSON string?
If it is an array, you want to iterate over its elements, or maybe just pull out the first one.
You could try using the NSRegularExpression to remove if any brackets existing in your code. You can find different combinations for regular expressions to use.
NSString *expression = #"\\s+\\([^()]*\\)";
while ([responseMessage rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location!=NSNotFound)
{
responseMessage = [responseMessage stringByReplacingOccurrencesOfString:expression withString:#"" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, [responseMessage length])];
}
NSLog(#"returnResponse %#",responseMessage);

Resources