Xcoder
Xcoder

Reputation: 199

Scan string, get info. Xcode

I have made an app which the user types in data and it gets a url from google maps like this - [https://www.google.com.au/maps/search/nearest+pizza+shop/@-27.4823545,153.0297855,12z/data=!3m1!4b1

In the middle you see 27.4823545,153.0297855 this is long and lat. So with this I can make my maps work. But I really need to know how to scan this string (the url was made into a string) and get only those numbers, I have already tried this ->

NSString *currentURL = web.request.URL.absoluteString;
    string1 = currentURL;



    NSScanner *scanner = [NSScanner scannerWithString:string1];
    NSString *token = nil;
    [scanner scanUpToString:@"@" intoString:NULL];
    [scanner scanUpToString:@"z" intoString:&token];

    label.text = token;

I think it would be highly likely I did a mistake, since I am new to objective-c, but if there are more effective ways please share . :)

Thanks for all the people who took the time to help. Bye All!

Upvotes: 0

Views: 192

Answers (1)

nstefan
nstefan

Reputation: 187

A solution: Extrating the path from an NSURL. Then looking at each path components to extract the coordinates components :

NSURL *url = [NSURL URLWithString:@"https://www.google.com.au/maps/search/nearest+pizza+shop/@-27.4823545,153.0297855,12z/data=!3m1!4b1"];
NSArray *components = [url.path componentsSeparatedByString:@"/"];
NSArray *results = nil;
for (NSString *comp in components) {
    if ([comp length] > 1 && [comp hasPrefix:@"@"]) {
        NSString *resultString = [comp substringFromIndex:1]; // removing the '@'
        results = [resultString componentsSeparatedByString:@","]; // lat, lon, zoom
        break;
    }
}
NSLog(@"results: %@", results);

Will print:

results: (
    "-27.4823545",
    "153.0297855",
    12z
)

This solution gives you a lot of control points for data validation. Hope this helps.

Edit:

To get rid of the "z". I would treat that as a special number with a number formatter in decimal style and specify that character as the positive and negative suffix:

NSString *targetStr = @"12z";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.positiveSuffix = @"z";
formatter.negativeSuffix = @"z";
NSNumber *result = [formatter numberFromString:targetStr];

The var result will contain whatever positive or negative number before the 'z'. You could use a NSScanner to do the trick but I believe it's less flexible.

As a side note, it would be great to get that "z" (zoom's character) from Google's API. If they ever change it to something else your number will still be parsed properly.

Upvotes: 2

Related Questions