开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜