iOS read CSV file by using CHCSVParser - iphone

Here is my code, and the csv file is
"Hello,Baby",Testing
ByeBye,Testing
When I print out the rowArray, I found that the result contain "
"Hello,Baby"
How can I remove it
- (IBAction)importToDatabase:(id)sender {
NSString *csvFilePath = [NSString stringWithFormat:#"%#/Documents/%#",NSHomeDirectory(),#"test1.csv"];
if([[NSFileManager defaultManager] fileExistsAtPath:csvFilePath])
NSLog(#"Exist");
else
NSLog(#"NOT EXIST");
NSArray *rowArray = [NSArray arrayWithContentsOfCSVFile:csvFilePath];
NSLog(#"%#",[[rowArray objectAtIndex:0]objectAtIndex:0]);
}

You can make use of the function stringByReplacingOccurrencesOfString:withString: to replace the " with a blank string (see the documentation). If have access to the code of the method arrayWithContentsOfCSVFile: you can did it in there, if not you will have to iterate throw the values of your array to remove it.

Related

How to convert text file to xml in xcode

I have a big text file that I want to convert into Xcode. I added the text file in the main bundle (drag and drop) into my project . I can see the text file viewDidLoad.
But I like to convert it to XML file. For instance my file looks like :
asasasasasas
wewewewewewe
qwqwqwqwqwqw
xyz_ 22 aaaaaaaaaaa
fgfgfgfgfgfgfg
ererererererer
abc_ 12 bbbbbbbbbb
jkjkjkjkjkjkjk
lalallalalalal
In the above mentioned, I want to eliminate the first 3 lines, to start from xyz_ 22 as (parent), jkjkjkj as child lalalala as a child.
I need only the idea how to implement this ... I'll write the code :)
mycode:
- (IBAction)readUsingObjectiveC:(id)pId {
NSString * zStr = [NSString stringWithContentsOfFile:#"/Users/dd007/Desktop/abc.txt" encoding:NSASCIIStringEncoding error:NULL];
NSLog(#"readUsingObjectiveC zStr=\n%#",zStr);
// now to extract the data line by line
NSArray * zAryOfLines = [zStr componentsSeparatedByString:#"\n"];
if([zAryOfLines count] == 0)
{
NSLog(#"readUsingObjectiveC zAryOfLines count = 0");
return;
}
//for (int i=0; i<([zAryOfLines count]-30); ++i)
for ( int i=30; i<zAryOfLines ; i++)
{
if([[zAryOfLines objectAtIndex:i] isEqualToString:#"xyz_ "])
{
NSLog(#"<msg1>%#<msg1/>\n",[zAryOfLines objectAtIndex:i]);
NSLog(#"<msg2>%#<msg2/>\n",[zAryOfLines objectAtIndex:i+1]);
NSLog(#"<msg3>%#<msg3/>\n",[zAryOfLines objectAtIndex:i+2]);
[zArrayOfLines writeToFIle:#"/.....documents/..save.xml" automatically:YES encodingNSASCIIStringEncoding error:NULL];
}
}
I am getting convert into xml format but i like to save the file in .xml .. but i am getting error could any one tell me where i am doing mistake ??????
You can't convert a file to xml using XCode, you have two options:
You can create a python or ruby script that parses your file and makes a XML file, and then use a xml parser,
Or you can create a class that parses your plain file with the rules you want.
I think you want to transform a .txt to a .xml so for make this i read the .txt to a nsstring i cut this into a NSArray with componentsSeparatedByString:#"\n" method of NSString (take care of \r character) and after just don't take line you don't want and create a new NSString for add tag XML to your line if you now where place the good tag or check it with the contains of your line in the NSArray for finish just saved in new file with extension .xml.
If you need help for write code like i describe say it.
There is no option for converting the text to xml directly in iOS.
But you can do it by passing the data manually.
You can use either libXml framework or GDataXml for doing this.
For libXml xml generation sample code go to this link and download Chapter 10.zip
Please check this tutorial for Read and Write XML Documents with GDataXML
Also TCMXMLWriter is an opensource xmlgenerator :
I think a code like this work for your example :
NSString *contentFile = [[NSString alloc] initWithContentsOfFile:pathFile encoding:NSUTF8StringEncoding error:nil];
NSArray *lineFile = [contentFile componentsSeparatedByString:#"\n"];
NSMutableString *xmlFile = [[NSMutableString alloc] init];
For(int i = 3; i < lineFile.count; i++)//i = 3 for don't take the 3 first line
{
if ([((NSString *)[lineFile objectAtIndex:i]) rangedOfString:#"test"].location != NSNotFound)
{
xmlFile = [NSString stringWithFormat:#"%#<nameTag>%#</nameTag>", xmlFile, (NSString *)[lineFile objectAtIndex:i]];
}
else if ...
}
And save he nsstring in new file. Possible in loop to make by number like if i is multiple of 3 of 4 etc...

Reading 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.
I use the following code but it checks only the first rows first column and not others... I call the function on button click...
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.
break;
}
}
Have you checked how many lines you've successfully split your input into? I'd guess that your input file is not linebreaked with \n but maybe \r...
If this is the problem, then you'll be interpreting the file as only having a single row. Check out this related answer for how to split into lines properly: How do I get each line from an NSString?. Depending on the version of iOS you're targeting, you can possibly use the method called out in the question itself.

Search for an array of substrings within a string

I want to check whether a string contains any of the substrings that I place in an array. Basically, I want to search the extensions of a file, and if the file is an "image", i want certain code to execute. The only way I can think of categorizing the file as an "Image" without downloading the file is through the substring in a string method. This is my code so far:
NSString *last5Chars = [folderName substringFromIndex: [folderName length] - 5];
NSRange textRangepdf;
textRangepdf =[last5Chars rangeOfString:#"pdf"];
if(textRangepdf.location != NSNotFound)
{
[self.itemType addObject:#"PDF.png"];
}
Is it possible to do this where I can check if last5Chars contains #"jpg" or #"gif" of #"png" etc...?? Thanks for helping!
NSString *fileName;
NSArray *imgExtArray; // put your file extensions in here
BOOL isImage = [imgExtArray containsObject:[fileName pathExtension]];
[folderName hasSuffix:#".jpg"] || [folderName hasSuffix:#".gif"]
obviously you can put it into a loop, if you have a whole arrayful.
Rather than mess about with ranges and suffixes, NSString has a method that treats an NSString as a path and returns an extension, it's called pathExtension.
Have a look in the NSString Documentation
Once you get the extension you can check it against whatever strings you want.

Finding a filename with a wildcard in iPhone SDK

I am trying to write a program that creates dynamically named .csv files that need to be either retrieved or deleted at a later run date. What I am trying to do is this:
I would like to run an algorithm that will find out if any of these types of files exist. For example, if I dynamically name the file something like foobar##.csv with the ## indicating a number being dynamically being generated and appended to the filename, I would like to find if any foobar##.csv file exists regardless of the number used. Normally I would use a line of code like this:
NSString *dataFileName = [[self documentPath] stringByAppendingPathComponent:#"foobar01.csv"];
Right now I just use a loop that cycles through each value and trips a bool if one is found, but I know this isn't a best practice as it limits the possible filename numbers the user can use. Any insight into how I could use some sort of wildcard on a search like this would be appreciated.
Also, I would want to create a method that would delete any .csv files the program finds, but I'm assuming that the method used to solve the above algorithm can be used for the deletion one as well.
Wildcard match
To match using a wildcard string the query can use like instead of the comparison operator and include the “*” (match zero or more characters) or “?” (match exactly 1 character) as wildcards as follows:
NSString *match = #"imagexyz*.png";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF like %#", match];
NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
http://useyourloaf.com/blog/2010/7/27/filtering-arrays-with-nspredicate.html
Take a look at NSFileManagers contentsOfDirectoryAtPath:error: method. It will return an array with strings containing the names of all objects (files and directories) of the directory in question.
You could then enumerate through that array and check for occurances of "foobar" in those strings. Either do something to the files you found right away or store the "positive" filenames in another array for later processing.
sample code for what the other poster said more or less.
+(NSMutableArray*) allocLocalFiles
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error = nil;
NSArray *origContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory
error:&error];
NSMutableArray * files = [[NSMutableArray alloc]init];
for (NSString* file in origContents) {
NSString * ext = [file pathExtension];
if ([ext compare:#"csv"]==0 && something_else)
{
[files addObject:
[NSString stringWithFormat:#"%#/%#",documentsDirectory,file]];
}
}
return files;
}

Open strings file from recource folder

I have a language file downloaded from a web service located in my resources folder of the project. The file name is "no.properties" and I need to load the file into a string to make further use of it..
The content of my file is displayed like this:
CMD_EXIT = Avslutt
CMD_PAUSE = Pause
CMD_SCAN = Skann
ect.....
Here is my code of loading the file into a string:
NSString* path = [[NSBundle mainBundle] pathForResource:[defaults objectForKey:#"language"]
ofType:#"properties"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
The problem is that the "content" string is null even though the file contains a lot of data. Anyone know what might be the problem?
note: I´ve checked that the value received from userdefaults equals "no". I have also tried to rename the file to "no.txt", but still the "content" string is null.
First, you could try to pass a NSError object to stringWithContentsOfFile:::.
You should receive a Cocoa error number, that (hopefully) tells you more about the problem.
NSError* err = nil;
NSString* string = [NSString stringWithContentsOfFile:path encoding:NSUTF16BigEndianStringEncoding error:&err];
As you seem to work with language files, I suspect that you are specifying the wrong encoding when reading in the strings.