How to convert csv file data into NSMutabledictionary - iphone

I want to parse the csv data with live link and convert the same in NSMutabledictionary.Here is the link that i am using for csv file.
http://ichart.yahoo.com/table.csv?s=BAS.DE&d=2&e=30&c=2012
Please help me out for the same.
Thanks in advance.

This link should have what you need. But, do you download that link as file into your app directory? If so, after importing parseCSV, it is fairly easy to go through the lines of the csv file:
CSVParser *parser = [CSVParser new];
NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:#"myCsvFile" ofType:#"csv"];
[parser openFile:csvFilePath];
NSArray *csvContentArray = [parser parseFile];
for (int i=0; i<csvContentArray.count; i++)
NSLog(#"parsed %d %#", i, [csvContentArray objectAtIndex:i]);
[parser closeFile];

Related

IOS and XML parser (reading file )

I am new in IOS. and i was looking for a tuto or small example in how to read from a local xml file in my ressources but i found nothing....any one with a good tuto or have worked with xml before i really need your help
Here you have the NSXMLParserDelegate doc with examples
You can use the following code for reading the xml file:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myLocalXML" ofType:#"xml"];
if (filePath)
{
NSString *myText = [NSString stringWithContentsOfFile:filePath];
if (myText)
{
NSLog(#"XML : %#",myText);
NSData *xmlData = [myText dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
parser.delegate = self;
[parser parse];
}
}
the following link will help you adding parser provided by apple
http://www.edumobile.org/iphone/iphone-programming-tutorials/parsing-an-xml-file/
NSString *path = [[NSBundle mainBundle] pathForResource:#"Name of your xml here...." ofType:#"xml"];
use the e above code to access file from your project and provide it to above parser for parsing
TBXML is my favorite. You can download project from git hub.
And why is this my favorite is because it's easy to understand and also it's performance is high.
Read this blog for more
How To Choose The Best XML Parser for Your iPhone Project

creating a binary (.bin) file and read values from file in iphone

Hi i am trying to save text values as binary file and read from that file. i am using following code, i got the binary file in documents directory but when reading data from file only got some numbers please kindly help its urgent.
For writing
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
NSLog(#"%#",documentsDirectoryPath);
if ([[NSFileManager defaultManager] isWritableFileAtPath:documentsDirectoryPath]) {
NSLog(#"content =%#",data_);
[data_ writeToFile:documentsDirectoryPath atomically:YES];
return YES;
}
For reading i use the following code,
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
if ([[NSFileManager defaultManager] isReadableFileAtPath:documentsDirectoryPath]) {
NSMutableData *data_ = [NSMutableData dataWithContentsOfFile:documentsDirectoryPath];
return data_;
}
I got only numbers from the data_ .
How to read the .bin file correctly.?
I got the .bin file when extract get .bin.cpgz file.I can't open the file what is the reason ?Is anything wrong in code?
I am pass string in this way:
[self writeData:#"test string is here" toFile:#"mf.bin"];
Thanks.
It's a little late, but something like this might help you:
http://snippets.aktagon.com/snippets/475-How-to-use-NSKeyedArchiver-to-store-user-settings-on-the-iPhone
Sounds like you need to convert the data into something readable.
NSString *myFile = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This assumes originally the data you wrote was a NSString, if it was an object you would have to use the appropriate methods for that object.

how to get data from file.txt into an NSMutableArray

I have file.txt data file in my project which is in resource folder.
Now i need to fetch the data from the file and load it into NSMutableArray.
how to approach to it.
First of all you need to read the file. And the you need to separate the string in components.
NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"test" ofType:#"txt"]
encoding:NSUTF8StringEncoding
error:nil];
NSMutableArray *stringsArray = [NSMutableArray arrayWithArray:[fileString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSLog(#"Array:%#",[stringsArray description]);
Good luck.

Load remote csv into CHCSVParser

I am using Dave DeLong's CHCSVParser to parse a csv. I can parse the csv locally, but I cannot get it load a remote csv file. I have been staring at my MacBook way too long today and the answer is right in front of me. Here is my code:
NSString *urlStr = [[NSString alloc] initWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"];
NSURL *lunchFileURL = [NSURL URLWithString:urlStr];
NSStringEncoding encoding = 0;
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVFile:[lunchFileURL path] usedEncoding:&encoding error:nil];
[p setParserDelegate:self];
[p parse];
[p release];
Thanks for any help that someone can give me.
-[NSURL path] is not doing what you're expecting.
If I have the URL http://stackoverflow.com/questions/4636428, then it's -path is /questions/4636428. When you pass that path to CHCSVParser, it's going to try and open that path on the local system. Since that file doesn't exist, you won't be able to open it.
What you need to do (as Walter points out) is download the CSV file locally, and then open it. You can download the file in several different ways (+[NSString stringWithContentsOfURL:...], NSURLConnection, etc). Once you've got either the file saved locally to disk or the string of CSV in memory, you can then pass it to the parser.
If this is a very big file, then you'll want to alloc/init a CHCSVParser with the path to the local copy of the CSV file. The parser will then read through it bit by bit and tell you what it finds via the delegate callbacks.
If the CSV file isn't very big, then you can do:
NSString * csv = ...; //the NSString containing the contents of the CSV file
NSArray * rows = [csv CSVComponents];
That will return an NSArray of NSArrays of NSStrings.
Similar to this last approach is using the NSArray category method:
NSString * csv = ...;
NSError * error = nil;
NSArray * rows = [NSArray arrayWithContentsOfCSVString:csv encoding:[csv fastestEncoding] error:&error];
This will return the same structure (an NSArray of NSArrays of NSStrings), but it will also provide you with an NSError object if it encounters a syntax error in the CSV file (ie, malformed CSV).
I think you need an NSString, not an NSURL object to pass to the parser so the extra part you are doing with changing the NSString to an NSURL is the issue. Looking at the CHCSVParser documentation, it looks like he wants NSString in the init.
So maybe you could do something like:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL] encoding:NSUTF8StringEncoding error:&err];
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVString:lunchFile usedEncoding:&encoding error:nil];

Convert Excel document (xls) to a plist

I have a pretty straightforward Excel spreadsheet, and I need to use the data in an iPhone app. The xls document has 6 columns, and > 200 rows.
I would like to create a plist from the xls document. How can I convert one to the other, programmatically?
I'm late to the party but I built a desktop utility that will convert CSV to a plist. You can download the binary or use this code, which requires cCSVParse. It uses whatever is in row 0 to create key names, then generates dictionaries for each successive row.
CSVParser *parser = [CSVParser new];
[parser openFileWithPath:pathAsString];
NSMutableArray *csvContent = [parser parseFile];
[parser closeFile];
if (pathAsString != nil)
{
NSArray *keyArray = [csvContent objectAtIndex:0];
NSMutableArray *plistOutputArray = [NSMutableArray array];
NSInteger i = 0;
for (NSArray *array in csvContent)
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSInteger keyNumber = 0;
for (NSString *string in array)
{
[dictionary setObject:string forKey:[keyArray objectAtIndex:keyNumber]];
keyNumber++;
}
if (i > 0)
{
[plistOutputArray addObject:dictionary];
}
i++;
}
NSMutableString *mutableString = [NSMutableString stringWithString:pathAsString];
[mutableString replaceOccurrencesOfString:#".csv" withString:#".plist" options:nil range:NSMakeRange([mutableString length]-4, 4)];
NSURL *url = [NSURL fileURLWithPath:mutableString];
[plistOutputArray writeToURL:url atomically:YES];
You could do this using a simple formula that you copy and pasted down a column beside each of your 200+ rows.
For example, assuming colum A contains a list of names, and column B contains a matching set of ages you could use a formula such as the following to end up with most of the XML for a plist based dictionary.
=CONCATENATE("<key>Name</key><string>", A1,"</string><key>Age</key><integer>",B1,"</integer>")
You then select all the cells within this new column you can copy and paste into notepad or another text editor to save it as a plist file (you may want to put some hardcoded text into a cell above and below your 200+ rows, in order to get the required tags etc as well...
Ladies and gentlemen,
I tried any other recommended solutions above but because of Unicode characters in my language (Turkish) none of them worked out for me... All unicode characters were all broken. Then I decided to make a tool for this.
I proudly present the simplest way to convert any XLS or XLSX or CVS file to a plist:
http://exceltoplist.herokuapp.com/
Just upload your XLS, XLSX or CSV and download your Apple Plist!
Enjoy!
Note: Because of Heroku's free dyno policy it might take a few moments to browse the page. Just keep waiting for 5-10 seconds to open page.
For OpenOffice, use this formula
=CONCATENATE("<key>number</key><integer>"; A2;"</integer><key>MyString</key><string>";B2;"</string>")
I found the CONCATENATE to work the best for this.
For my purpose I just need to convert CSV with two columns to plist file.
First column is keys and second are values. So, I slightly change Danilo Campos code as following:
CSVParser *parser = [CSVParser new];
[parser openFileWithPath:pathAsString];
NSMutableArray *csvContent = [parser parseFile];
[parser closeFile];
if (pathAsString != nil)
{
NSMutableDictionary *plistOutputArray = [NSMutableDictionary dictionary];
for (NSArray *array in csvContent)
{
NSString *key = (NSString *)([array objectAtIndex:0]);
NSString *value = (NSString *)([array objectAtIndex:1]);
[plistOutputArray setObject:value forKey:key];
}
NSMutableString *mutableString = [NSMutableString stringWithString:pathAsString];
[mutableString replaceOccurrencesOfString:#".csv" withString:#".plist" options:nil range:NSMakeRange([mutableString length]-4, 4)];
NSURL *url = [NSURL fileURLWithPath:mutableString];
[plistOutputArray writeToURL:url atomically:YES];
}
P.S. You can find his initial source code here - http://code.google.com/p/danilobits/source/checkout
Please note that to get his code work now you need to change "Base SDK" to "Latest OS X"
Use http://shancarter.github.io/mr-data-converter/ to convert xls to a Json(just copy & paste)(can re format it by remove white space in http://jsonviewer.stack.hu/). save json to text file named: in.json.
Use plutil command to format json to plist
plutil -convert xml1 in.json -o out.plist