最近项目中使用苹果自带的定位,但是解析完,得到的楼层信息不准确,所以想去掉楼层信息,
系统提供的API楼层信息直接包含在街道信息里,既想要街道信息又不想要楼层信息,就只能找偏方了,
于是我就投机取巧, 直接截串了,把后面带xx层的部分截掉.
下面是我的实现方案
- (void )getDetailAddressWithLocation:(CLLocation *)location{
// 反地理编码
// CLLocation * loc1 = [[CLLocation alloc] initWithLatitude:39.8 longitude:116.7];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if (placemarks.count)
{
CLPlacemark *placemark = placemarks.firstObject;
NSString *address = [placemark.addressDictionary[@"FormattedAddressLines"] firstObject];
// 如果是中国 去掉国家信息
if ([address hasPrefix:@"中国"]) {
address = [address substringFromIndex:2];
}
// 去掉楼层信息
NSString *lastChar = [address substringFromIndex:address.length-1];
if ([lastChar isEqualToString:@"层"]) {
// 去掉层
address = [address substringToIndex:address.length-1];
lastChar = [address substringFromIndex:address.length-1];
// 匹配数字
NSString *regex = @"\\d$";
NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
// 如果最后一个字符是数字(例如xxx3号楼2层)
while ((![lastChar isEqualToString:@"楼"]) && address.length > 1 && [regExPredicate evaluateWithObject:lastChar])
{
address = [address substringToIndex:address.length-1];
lastChar = [address substringFromIndex:address.length-1];
}
}
_addressLabel.text = address;
}
}];
}
如果大家有什么比较好的办法,还请多多指教