开发者

How would you parse the location text from Twitter to get the latitude/longitude in Objective-C?

开发者 https://www.devze.com 2022-12-25 20:55 出处:网络
The location text from Twitter could be just about anything. Sometimes Twitter clients set the location with the user\'s latitude and longitude in the following format.

The location text from Twitter could be just about anything. Sometimes Twitter clients set the location with the user's latitude and longitude in the following format.

"\U00dcT: 43.05948,-87.908409"

Since there is no built-in support for Regular Expressions in Objective-C I am considering using the NSString functions like rangeOfString to pull the float values out of this string.

For my current purpose I know the values with start with 43 and 87 so I can key off th开发者_如何转开发ose values this time but I would prefer to do better than that.

What would you do to parse the latitude/longitude from this string?


This way won't create nearly as many intermediate objects:

float latitude, longitude;
NSString *exampleString = @"\U00dcT: 43.05948,-87.908409";
NSScanner *scanner = [NSScanner scannerWithString:exampleString];
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
[scanner scanUpToCharactersFromSet:digits intoString:null];
[scanner scanFloat:&lattitude];
[scanner scanUpToCharactersFromSet:digits intoString:null];
[scanner scanFloat:&longitude];


This appears to work well but I am still interested in what other approaches could work better.

- (CLLocation *)parseLocationText:(NSString *)lt {
    // location = "\U00dcT: 43.05948,-87.908409";

    NSString *strippedString = [lt stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];
    NSLog(@"strippedString: %@", strippedString);

    if ([strippedString rangeOfString:@","].location != NSNotFound) {
        NSArray *chunks = [strippedString componentsSeparatedByString: @","];
        if (chunks.count == 2) {
            NSLog(@"lat: %@", [chunks objectAtIndex:0]);
            NSLog(@"long: %@", [chunks objectAtIndex:1]);

            NSString *latitude = [chunks objectAtIndex:0];
            NSString *longitude = [chunks objectAtIndex:1];
            CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
            [loc autorelease];
            return loc;
        }
    }

    return nil;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消