Suraj Sukale Suraj Sukale - 6 months ago 21
iOS Question

How to separate parameter from Output

I'm creating simple project in which i want users location(latitude and longitude).I did it successfully.
I'm getting output like this

<+37.33370957,-122.06381723> +/- 5.00m (speed 34.53 mps / course 294.26) @ 5/26/16, 3:38:54 PM India Standard Time

I want to send Latitude and longitude separately to server,
Now my question is how should i separate that lat-long from above output. means I want to separate
+37.33370957
this in one string and
-122.06381723
this is another string... How can i do like this??
please suggest any solution for this issue...!

Answer

This should work:

NSString *rawString = @"<+37.33370957,-122.06381723> +/- 5.00m (speed 34.53 mps / course 294.26) @ 5/26/16, 3:38:54 PM India Standard Time";
NSRange range1 = [rawString rangeOfString:@"<"];
NSRange range2 = [rawString rangeOfString:@">"];
NSString *string = [rawString substringWithRange:NSMakeRange(range1.location + range1.length, range2.location - range1.location - range1.length)];
NSArray *components = [string componentsSeparatedByString:@","];
NSString *latitude = [components objectAtIndex:0];
NSString *longitude = [components objectAtIndex:1];

Another way:

NSString *rawString = @"<+37.33370957,-122.06381723> +/- 5.00m (speed 34.53 mps / course 294.26) @ 5/26/16, 3:38:54 PM India Standard Time";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\<)(.*?)(?=\\>)" options:NSRegularExpressionCaseInsensitive error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:rawString options:0 range:NSMakeRange(0, [rawString length])];
NSArray *components = [[rawString substringWithRange:[match rangeAtIndex:0]] componentsSeparatedByString:@","];
NSString *latitude = [components objectAtIndex:0];
NSString *longitude = [components objectAtIndex:1];

Probably there's even a better way with regex but sadly I'm not good at it.