Search in .csv file - iphone

I have an .csv file with round about 10.000 Lines.
Now I have a textfield in which the User typing a value than he Click on a Button.
Now this value should be searching in the .csv and then in this Linie all values should be Displayed in a Label
E.g.
.csv:
PLZ, Name, Code 47158, Neuss, DE005116 46356, Moers, DE006151
ViewControler:
Textfield search: 47158
Label1: Neuss
Label2: DE005116
Thanks for helping

1 google search would have made you happy ;)
http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
EDIT To answer your question below.
while ([scanner scanFloat:&myVariable] && [scanner scanFloat:&myVariable2] && [scanner scanFloat:&myVariable3]) {
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:myVariable], #"theKeyInTheCSV",
[NSNumber numberWithFloat:myVariable2], #"theKeyInTheCSV2",
[NSNumber numberWithFloat:myVariable3], #"theKeyInTheCSV3",
nil]];
}

her is my code:
-(IBAction)Zollamtsname:(id)sender{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Zollämter Access" ofType:#"csv"];
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
NSLog(#"%#", [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]);
if ( nil == mytext ) return NO;
NSScanner *scanner = [NSScanner scannerWithString:myText];
[scanner setCharactersToBeSkipped:
[NSCharacterSet characterSetWithCharactersInString:#"\n, "]];
NSMutableArray *newPoints = [NSMutableArray array];
float test1, test2;
while ( [scanner scanFloat:&test1] && [scanner scanFloat:&test2] ) {
[newPoints addObject:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:test1], #"test1",
[NSNumber numberWithFloat:test2], #"test2",
nil]];
}
[self setPoints:newPoints];
return YES;
}
//[self.Zollamzsnummer setText:#"test"];
}
i get 4 errors and I don't know how so solve them :( 1."return NO" = the void method should not return a value
2. "return YES" = the void method should not return a value
3. [self setPoints:newPoints]; = Not visible #interface for'ViewController_suche'declares the selector setPoints
ANd who I say that the serach value is in the textfield?

Related

Getting substring from response NSString

I need to get substring CODE's value (X2.31) from string
NSString *str = #"SHMU=\"\" CODE=\"X2.31\" XTN=\";
How could I get that particular substring?
Try the below one
NSString *str = #"SHMU=\"\" CODE=\"X2.31\" XTN=\"";
NSRange range = [str rangeOfString:#"CODE="];
NSString *substring = [[str substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *str1 = [substring componentsSeparatedByString:#" "];
NSLog(#"the sub %#",[[str1 objectAtIndex:0] stringByTrimmingCharactersInSet[NSCharacterSet whitespaceCharacterSet]]);
And by string was "X2.31"
NSString *strOrg = [NSString stringWithFormat:#"%#",#"SHMU=\"\" CODE=\"X2.31\" XTN=\""] ;
NSString *strLeft = [NSString stringWithFormat:#"%#",#"SHMU=\"\" CODE=\""] ;
NSString *strRight = [NSString stringWithFormat:#"%#",#"\" XTN=\""] ;
NSLog(#"%#", [self getDataBetweenString:strOrg LeftString:strLeft RightString:strRight LeftOffset:13]);
- (NSString *)getDataBetweenString:(NSString *)orgString LeftString:(NSString *)leftString RightString:(NSString *)rightString LeftOffset:(NSInteger)leftPos;
{
NSInteger left, right;
NSString *foundData;
NSScanner *scanner=[NSScanner scannerWithString:orgString];
[scanner scanUpToString:leftString intoString: nil];
left = [scanner scanLocation];
[scanner setScanLocation:left + leftPos];
[scanner scanUpToString:rightString intoString: nil];
right = [scanner scanLocation] + 1;
left += leftPos;
foundData = [orgString substringWithRange: NSMakeRange(left, (right - left) - 1)]; return foundData;
}
This is only specific to the str you posted.
Your number must be followed by First X.
float f=[[str componentsSeparatedByString:#"X"][1] floatValue];

How can I extract parameters from a non-standard URL NSString object?

I'm diving into iOS development and I have a custom URL scheme for my iPhone app that looks like myApp://?q=200. I have the following code to get the query parameter...
NSString *urlString = [url absoluteString];
NSString *query = [urlString stringByReplacingOccurrencesOfString:#"myApp://?q=" withString:#""];
...but I'd like to make it a bit more future-proof in the event that I add more parameters. How can I extract the "q" parameter in a safer way?
Thanks in advance for your wisdom!
You can split the query returned from the URL by & and = and put them in a dictionary.
NSURL *url = [NSURL URLWithString:#"myApp://?q=200"];
NSArray *query = [[url query] componentsSeparatedByString:#"&"];
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[query count]];
for(NSString *parameter in query)
{
NSArray *kv = [parameter componentsSeparatedByString:#"="];
[parameters setObject:[kv count] > 1 ? [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding] : [NSNull null]
forKey:[[kv objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];
}
NSLog(#"Parameters: %#", parameters);
NSLog(#"q = %#", [parameters objectForKey:#"q"]);
In this example if there is no value for the parameter I just set it to NSNull. This means you would either need to check for NSNull or change the logic to skip keys with values or set them to an empty string.
This from the top of my head could work but doesnt yet include error checking the input
-(NSDictionary*) parameterDictionaryFromString: (NSURL*) url {
//input can be something like: "myApp://?q=one&q2=two&q3=three"
NSString *requestString = [url query];
//now we have q=one&q2=two&q3=three
NSArray *requests = [requestString componentsSeparatedByString: #"&"];
NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];
for (NSString *singleParameter in requests) {
NSArray *keyValuePair = [singleParameter componentsSeparatedByString: #"="];
[resultDictionary setObject: [keyValuePair objectAtIndex: 1] forKey: [keyValuePair objectAtIndex: 0]];
}
NSURL *u = [NSURL URLWithString: #"myApp://something?q=1&check=yes"];
NSLog(#"paramStr = %#", [u parameterString]);
return [resultDictionary copy];
}
Break the Query String by Distinct Separator,
Assure Valued Content provided at index:1 (The right-hand side of the query string break)
In valued content then use downstream, or set to upstream variable.
//Your Example:
//#"myApp://?q=200"
//Break:
NSArray *queryParts = [urlString componentsSeparatedByString:#"?q="];
//Assure Content:
if ([[array objectAtIndex:1] length]>0) {
//Setter:
NSString *queryString = [array objectAtIndex:1];
//... Use away...
}
The key is to leverage the NSArray class over StringReplace.

Problem with CGImageDestination and file naming

I am capturing images from the camera, using AVCapture as I have need of speed and the standard kit stuff is way too slow.
I have problem whereby the file that is being output (an animated GIF) is having it's file name mangles by the CGImageDestination functions...
When I output the NSURL (cast to a CFURLRef) to the log I get the path/filename I intended:
2011-09-04 20:40:25.914 Mover[3558:707] Path as string:.../Documents/91B2C5E8-F925-47F3-B539-15185F640828-3558-000003327A227485.gif
However, once the file is created and saved it actually lists the filename as this:
2011-09-04 20:40:25.960 Mover[3558:707] file: .91B2C5E8-F925-47F3-B539-15185F640828-3558-000003327A227485.gif-TtNT
See the difference? the period at the start and the 4 character suffix?
Whats really wierd is that it doesn't always do it, about 40% of the time it works OK. However it's preventing the code working further down the line where I'm listing them with previews in a table view.
Does anyone know why and how to stop it doing this?
Here's the code:
- (void)exportAnimatedGif{
NSString *guidPath = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *tmpPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:guidPath];
NSString *path = [tmpPath stringByAppendingPathExtension:#"gif"];
NSLog(#"Path as string:%#", path);
CGImageDestinationRef destination = CGImageDestinationCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], kUTTypeGIF, [captureArray count], NULL);
NSDictionary *frameProperties = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:testDisplay3.displayValue] forKey:(NSString *)kCGImagePropertyGIFDelayTime]
forKey:(NSString *)kCGImagePropertyGIFDictionary];
NSDictionary *gifProperties = [NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:2], (NSString *)kCGImagePropertyGIFLoopCount,
[NSNumber numberWithFloat:testDisplay3.displayValue], (NSString*)kCGImagePropertyGIFDelayTime,
[NSNumber numberWithFloat:testDisplay3.displayValue], (NSString*)kCGImagePropertyGIFUnclampedDelayTime,
nil]
forKey:(NSString *)kCGImagePropertyGIFDictionary];
for (int ii = 0; ii < [captureArray count]; ii++)
{
UIImage *tmpImg = [[UIImage alloc] init];
tmpImg = [captureArray objectAtIndex:ii];
CGImageDestinationAddImage(destination, tmpImg.CGImage, (CFDictionaryRef)frameProperties);
}
CGImageDestinationSetProperties(destination, (CFDictionaryRef)gifProperties);
CGImageDestinationFinalize(destination);
CFRelease(destination);
//TEST OUTPUT GENERATED FILES
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:nil];
for (int xx = 0; xx < [contents count]; xx++)
{
NSLog(#"file: %#", [contents objectAtIndex:xx]);
}
//END TEST CODE
[captureArray removeAllObjects];
}
AFAIK this is a temporary file that CGImageDestinationFinalize makes, the reason you see them is that CGImageDestinationFinalize failed. I think that if you check the file sizes you'll see that the ones with mangled names have a file size of 0.
I started check for succes after I got these files :)
bool success = CGImageDestinationFinalize(destination);
CFRelease(destination);
if (success) {
NSLog(#"animated GIF file created at %#", path);
} else {
NSLog(#"failed to create gif at %#", path);
}

Build string with variable number of keys and formats

I have an NSDictionary object that contains my data. I am passing in an array of key names and a display format for a string representation of my data.
[self displayMyDataWithTheseKeys:myKeyArray inThisFormat:myFormat];
where, for example,
myKeyArray = [NSArray arrayWithObjects: #"Key1", #"Key2", nil];
myFormat = [NSString stringWithString: #"%# to the %# degree"];
However, myFormat may change and the number of keys in the array may vary as well.
If the number of elements in the array was always 2, this would be trivial. However, how can I handle a variable number of elements?
There isn't really a built-in method for this, but it's relatively easy to parse format strings with NSScanner. Here's a simple example, it only handles %# format specifiers, but as all elements in an NSArray are objects and not primitive types anyway, it shouldn't matter:
NSArray *myKeyArray = [NSArray arrayWithObjects: #"Key1", #"Key2", nil];
NSString *myFormat = [NSString stringWithString: #"%# to the %# degree"];
NSMutableString *result = [NSMutableString string];
NSScanner *scanner = [NSScanner scannerWithString:myFormat];
[scanner setCharactersToBeSkipped:[NSCharacterSet illegalCharacterSet]];
int i = 0;
while (![scanner isAtEnd]) {
BOOL scanned = [scanner scanString:#"%#" intoString:NULL];
if (scanned) {
if (i < [myKeyArray count]) {
[result appendString:[myKeyArray objectAtIndex:i]];
i++;
} else {
//Handle error: Number of format specifiers doesn't
//match number of keys in array...
}
}
NSString *chunk = nil;
[scanner scanUpToString:#"%#" intoString:&chunk];
if (chunk) {
[result appendString:chunk];
}
}
Use: stringByAppendingString
Here's an example on how to use it:
NSString *someString = #"String";
someString = [someString stringByAppendingString:[NSString stringWithFormat:#"%#",variable1]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:#"%#",variable2]];
someString = [someString stringByAppendingString:[NSString stringWithFormat:#"%#",variable3]];
...and so on
If you have an array of keys which you want to put in a string:
NSString *string = #"And the keys are:\n";
for(int i = 0; i < [array count]; i++)
{
NSString *thisKey = (NSString *)[array objectAtIndex:i];
string = [string stringByAppendingString:[NSString stringWithFormat:#"Key number %d is %#",i,thisKey]];
}

Load data from csv file (iphone SDk)

Does anyone know how to load data from csv file?
For the code example,
CPTestAppScatterPlotController.m
that I downloaded from core-plot Google website, a line graph can be plotted based on randomly
generated initial data x, y.
// Add some initial data
SMutableArray *contentArray = [NSMutableArray arrayWithCapacity:100];
NSUInteger i;
for ( i = 0; i < 60; i++ ) {
id x = [NSNumber numberWithFloat:1+i*0.05];
id y = [NSNumber numberWithFloat:1.2*rand()/(float)RAND_MAX + 1.2];
[contentArray addObject:[NSMutableDictionary
dictionaryWithObjectsAndKeys:x, #"x", y, #"y", nil]];
}
self.dataForPlot = contentArray;
Then i modified the code,
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"ECG_Data" ofType:#"csv"];
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
NSScanner *scanner = [NSScanner scannerWithString:myText];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:#"\n, "]];
NSMutableArray *newPoints = [NSMutableArray array];
float time, data;
while ( [scanner scanFloat:&time] && [scanner scanFloat:&data] ) {
[newPoints addObject:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:time], #"time",
[NSNumber numberWithFloat:data], #"data",
nil]];
}
self.dataForPlot = newPoints;
It seems that my code could not read the data from csv file.
(there are two cols of the data in ECG_Data.csv, one for time and one for data)
Can anyone give me some suggestion???
Thanks!!!!
http://cocoawithlove.com/2009/11/writing-parser-using-nsscanner-csv.html
Here is a good place to start for creating a CSV parser. It's complete with sample code and user comments.