CLPlacemark - State Abbreviations?

后端 未结 7 1472
隐瞒了意图╮
隐瞒了意图╮ 2021-02-19 00:24

I was wondering if it was possible to get the state abbreviations from CLPlacemark?

In the CLPlacemark Reference from Apple it states:

administrativeArea The sta

7条回答
  •  孤独总比滥情好
    2021-02-19 00:53

    Here is another category using FormattedAddressLines, it returns a result like California, CA

    -(NSString *) stateWithAbbreviation {
    if ([[self.addressDictionary objectForKey:@"CountryCode"] isEqualToString:@"US"] && self.addressDictionary) {
        NSDictionary *addressLines = [self.addressDictionary objectForKey:@"FormattedAddressLines"];
        for (NSString* addressLine in addressLines) {
            NSRange stateRange = [addressLine rangeOfString:self.postalCode options:NSCaseInsensitiveSearch];
            if (stateRange.length > 0) {
                NSRange lastSpace = [addressLine rangeOfString:@" " options:NSBackwardsSearch];
                if (lastSpace.length > 0) {
                    NSString *state = [[addressLine substringToIndex:lastSpace.location] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                    lastSpace = [state rangeOfString:@" " options:NSBackwardsSearch];
                    if (lastSpace.length > 0) {
                        NSString *abbr =  [[state substringFromIndex:lastSpace.location] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                        return  [NSString stringWithFormat:@"%@, %@", self.administrativeArea, abbr];
                    }
                }
            }
        }
    }
    return self.administrativeArea;
    }
    

    Not perfect but it works as long as Apple changes the format of the address lines I think.

提交回复
热议问题