Reading the first column data from CSV file and compare it with user input? - iphone

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.

Related

strange NSString behaviour when used with [NSBundle mainBundle] pathForResource

I have a weird one for you guys today, I think my NSStrings are incorrectly encoded.
NSString * convertedString = [NSString stringWithUTF8String:mesh->groupMesh[i].materialData->textureName];
-textureName is just a c style string that I'm converting into an NSString.
-The string is: "dennum1.png"
NSArray * line = [convertedString componentsSeparatedByString:#"."];
NSString * texPath = [[NSBundle mainBundle] pathForResource:line[0] ofType:line[1]];
I then split it into an NSArray line, separated by periods "."
This makes it so that line[0] is dennum1, and line[1] is png.
I even do an NSLog to make sure:
NSLog(#"Name:%# Type:%#", line[0], line[1]);
2013-09-21 02:15:27.386 SteveZissou[8846:c07] Name:dennum1 Type:png
I parse this over to the pathForResource function and I get a (null) response.
BUT if I hard type the file name into the code I.E:
convertedString = #"dennum1.png";
NSArray * line = [convertedString componentsSeparatedByString:#"."];
NSString * texPath = [[NSBundle mainBundle] pathForResource:line[0] ofType:line[1]];
NSLog(#"This is the texPath: %#",texPath);
IT WORKS?!
This is the texPath: /Users/meow/Library/Application Support/iPhone Simulator/6.0/Applications/2DEB8076-5F9D-45DE-8A73-10B1C8A084B4/SteveZissou.app/dennum1.png
Is it possible that the NSString that I hard type in the code and the NSString that comes from the conversion are encoded differently?
When I NSLog them individually I get the same result regardless of type:
2013-09-21 02:15:27.386 SteveZissou[8846:c07] This is the c style string: dennum1.png
2013-09-21 02:15:27.386 SteveZissou[8846:c07] This is the converted c style string: dennum1.png
2013-09-21 02:15:27.386 SteveZissou[8846:c07] This is the string manually typed in: dennum1.png
What happens if you use the methods in NSPathUtilities that are designed to handle this stuff. Like:
NSString * texPath = [[NSBundle mainBundle] pathForResource:string.stringByDeletingPathExtension ofType:string.pathExtension];
Also, there's -fileSystemRepresentation which will convert an NSString to a const char * and throw an exception if the string can't be converted correctly.
I figured it out after HOURS of skimming through possible code combinations and found it by accident.
I used NSURL functions to get the path based on the strings I was using, which resulted in this path:
file://localhost/Users/meow/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/2DEB8076-5F9D-45DE-8A73-10B1C8A084B4/SteveZissou.app/dennum2.png%0D
Look at the very end! That's not supposed to be there! Turns out it's called a carriage return and it was pulled with the file (probably a remnant of the files formatting), but invisible to NSLog, however it wasn't invisible to NSURL (NSURL must read the bytes and display what they are?). So snipping the carriage return off the end of the path gave me the correct file and everything is OK.
I kept thinking to myself to use a hex editor to look at the file, but couldn't find one on the mac appstore free, I think if this was windows I would've caught it in half the time.

iOS read CSV file by using CHCSVParser

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.

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...

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;
}