NSString parsing - iphone

I need to parse this string into three different components:
Location: 1|#69.83623|#24.432223|#Cupertino, California
The value is stored in one NSString. I need it in three different strings. One string for latitude, one for longitude and one for location.
Any idea how I can do that?
Thanks!

You can use this method to get an array of different components:
NSArray *bits = [locationString componentsSeparatedByString: #"|#"];
Each item in the NSArray will be an NSString.

Try the following
NSString *location = #"1|#69.83623|#24.432223|#Cupertino, California";
NSArray *components = [location componentsSeparatedByString:#"|#"];
NSLog(#"%#",components);
float latitude = [[components objectAtIndex:1] floatValue];
float longitude = [[components objectAtIndex:2] floatValue];
NSString *loc = [components objectAtIndex:3];

NSString *t = #"Location: 1|#69.83623|#24.432223|#Cupertino, California";
NSArray *k = [t componentsSeparatedByString:#"|"];
NSLog(#"components %#", k);

Related

Add annotations to a MapView in a loop

I am trying to add some annotations to my mkMapView in this loop:
for (PFObject *fetchedCompany in companyArray)
{
Store *store = [[Store alloc] initWithObject:fetchedCompany];
[self loadStore:store];
[store release];
}
- (void) loadStore:(Store *) store {
CLLocationCoordinate2D location = [self getLocationFromAddressString:store.address];
MapViewAnnotation *mapAnnotation = [[MapViewAnnotation alloc] initWithTitle:store.name coordinate:location];
[self.indexMapView addAnnotation:mapAnnotation];
}
And this the getLocationFromAddressString method that convert the address to a location using google api:
-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {
NSString *urlStr = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=csv", [addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr] encoding:NSUTF8StringEncoding error:&error];
NSArray *items = [locationStr componentsSeparatedByString:#","];
double lat = 0.0;
double lon = 0.0;
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:#"200"]) {
lat = [[items objectAtIndex:2] doubleValue];
lon = [[items objectAtIndex:3] doubleValue];
}
else {
NSLog(#"Address, %# not found: Error %#",addressStr, [items objectAtIndex:0]);
}
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
return location;
}
When I send just one location always it works perfectly, but when I add annotations in my loop sometimes some locations could not be recognized and I got the error from my NSLog:
Address, Vallgatan 3 GĂ–TEBORG not found: Error 620
The thing is I am pretty sure about the addresses because when I tried them without loop they worked. Do you know how can I solve the problem?
You've submitted too many queries and your request got rejected. See Geocoding API V2 docs.
620: G_GEO_TOO_MANY_QUERIES
"The given key has gone over the requests limit in the 24 hour period or has submitted too many requests in too short a period of time. If you're sending multiple requests in parallel or in a tight loop, use a timer or pause in your code to make sure you don't send the requests too quickly"

componentsSeparatedByString return wrong result

I used this code to cut the string
NSString *titleString = #"22.225453615805794,113.554006577014889";
NSArray *array = [titleString componentsSeparatedByString:#","];
NSLog(#"title string %#", titleString);
NSLog(#"first %.15f", [[array objectAtIndex:0] floatValue]);
NSLog(#"second %.15f", [[array objectAtIndex:1] floatValue]);
but why it return
22.225454330444336
and
113.554008483886719
Because floating point numbers are not that accurate, you can get a higher accuracy by calling doubleValue instead of floatValue:
NSLog(#"second %.15f", [[array objectAtIndex:1] doubleValue]);
This is not a problem with componentsSeparatedByString:.
I think there is problem in converting string into float. Try using double.

How can I get an integer value from NSString in an iPhone application?

NSString * str=[zoneDict objectForKey:#"name"];
NSLog(#"==========string zone::==========%#",str);
// str="(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
How can I get the 3:00 value from the above string?
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSRange endRange = [str rangeOfString:#")"];
NSString *timeString = [str substringWithRange:NSMakeRange(5, endRange.location-5)];
NSRange separatorRange = [timeString rangeOfString:#":"];
NSInteger hourInt = [[timeString substringWithRange:NSMakeRange(0, separatorRange.location)] intValue];
NSLog(#"Hour:%d",hourInt);
Rather than trying to extract the time offset from the string, is there any way you could store actual time zone data in your zoneDict? For example you could store NSTimeZone instances instead.
If all you have is the string, you could use an NSRegularExpression object and extract the relevant information using a regular expression instead.
If you could explain further what you're trying to do then there may be an alternative way to achieve what you want.
I like to use -[NSString componentsSeparatedByString]:
NSString *str = #"(GMT -3:00) Baghdad, Riyadh, Moscow, St. Petersbur";
NSArray *myWords = [myString componentsSeparatedByString:#")"];
NSString *temp1 = [myWords objectAtIndex:0];
if ([temp1 rangeOfString:#"-"].location == NSNotFound) {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"+"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
else {
NSArray *temp2 = [temp1 componentsSeparatedByString:#"-"];
NSString *temp3 = [temp2 objectAtIndex:1];
NSLog(#"Your String - %#", temp3);
}
Output:
Your String - 3:00
Using regular expressions is the better option in my view (if you are forced to extract the '3' only). The regular expression string would contain something like "\d?" but don't quote me on that, you'll have to look up the exact string. Perhaps someone on here could provide the exact string.

distance from CurrentLocation to data from Plist File

I have a long list of places with Latitudes and Longitudes in a plist. I want to show a tableView of the places only within X distance of the user's current location. Is there a way to create objects from the lats & longs in the plist file so I can use 'distanceFromLocation'? More importantly, how do I get the array to only display the names with a distance from current less than X? I'm assuming I would need to make a series of objects from lats & longs in the plist, then do an objects in array if objects distanceFrom is less than X, correct?
Please help.
Here's where I am now: I get an error on the double clubLatitude line
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *clubArray = [NSArray arrayWithObjects:[self danceClubLocation], nil];
self.tableData = clubArray;
}
-(CLLocation *)danceClubLocation
{
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:plistPath];
NSEnumerator *e = [array objectEnumerator];
id object;
while ((object = [e nextObject])) {
double clubLatitude = [[array valueForKey:#"Latitude"] doubleValue];
double clubLongitude = [[array valueForKey:#"Longitude"] doubleValue];
CLLocation *clubLocation = [[CLLocation alloc] initWithLatitude:clubLatitude longitude:clubLongitude];
if ([clubLocation distanceFromLocation:myLocation]<=50) {
return clubLocation;
}
else return nil;
}
return nil;
}
-(CLLocation *)myLocation
{
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
NSNumber *myLatitude = [NSNumber numberWithDouble:coordinate.latitude];
NSNumber *myLongitude = [NSNumber numberWithDouble:coordinate.longitude];
double myLatitudeD = [myLatitude doubleValue];
double myLongitudeD = [myLongitude doubleValue];
myLocation = [[CLLocation alloc]initWithLatitude:myLatitudeD longitude:myLongitudeD];
return myLocation;
}
As #DavidNeiss said, you have to iterate over the list (an NSArray with the plist as source) and it would be something like this:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"latlong" ofType:#"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:plistPath];
NSEnumerator *e = [array objectEnumerator];
id object;
while (object = [e nextObject]) {
// do something with object
}
Then you can do what you want (removing what's far from the user or whatever).
Read in your plist, iterate over it to pull out ones within X distance and populate any array with them that will be the data source for your table view?

NSString: fastes way of splitting

my question is a performance question.
I need to split a huge NSString into coordinates. The string has this format:
#"coordx,coordy coordx,coordy coordx,coordy (...)"
My method to parse this is:
-(NSMutableArray*) parsePath:(NSString*) pathString
{
// first split between the coordinates
NSArray* path = [pathString componentsSeparatedByString:#" "];
NSMutableArray* coords = [[NSMutableArray alloc] init];
static NSString *seperator = #",";
NSArray *coord;
for(NSString *coordString in path)
{
coord = [coordString componentsSeparatedByString:seperator];
Coordinate *c = [[Coordinate alloc]init];
c.x = [[coord objectAtIndex:0] intValue];
c.y = [[coord objectAtIndex:1] intValue];
[coords addObject:c];
[c release];
}
return coords;
}
So, is there any way to make this faster?
Thanks!
Sebastian
Using NSScanner is probably faster.
http://developer.apple.com/iphone/library/documentation/cocoa/reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html