我使用 OSX 数据检测器从文本中提取地址。这为我提供了地址字符串,例如“1 Infinite Loop, Cupertino, CA”。
为了将这些地址放入 OSX 地址簿中,我必须将它们转换为带有“Street”、“City”、“Country”等键的字典”等
我知道有一个函数可以执行相反的操作:ABCreateStringWithAddressDictionary(...)
,但我需要以另一种方式。
我知道可以做到这一点的唯一方法(当然,完全是多余的)是将地址字符串发送到 CLGeocoder,它返回地址的坐标,然后再次发送坐标用于反向地理编码,返回包含地址字典的地标。
必须有一种更简单的方法来做到这一点。
编辑:
我现在学会了,
1)这个问题确实很复杂,并且最好通过使用地理编码服务器来解决,请参见例如here ,
2) 只需联系地理编码服务器一次就足够了:当向地理编码服务器发送地址字符串时,会发回地址目录。
最佳答案
如果您使用的是 NSTextCheckingTypeAddress
类型的数据检测器,则返回的匹配项应提供 addressComponents字典。
该字典包含您提到的所有键。
NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress error:nil];
NSString* addressString = @"Apple, 1 Infinite Loop, Cupertino, CA";
NSArray* matches = [detector matchesInString:addressString options:0 range:NSMakeRange(0, addressString.length)];
for(NSTextCheckingResult* match in matches)
{
if(match.resultType == NSTextCheckingTypeAddress)
{
NSDictionary* addressComponents = [match addressComponents];
NSLog(@"Address Dictionary:%@", addressComponents);
}
}
上面的代码片段返回以下输入字符串:
Address Dictionary:{
City = Cupertino;
State = CA;
Street = "1 Infinite Loop";
}
功能齐全的地址字符串将产生以下键的值:
NSTextCheckingNameKey
NSTextCheckingJobTitleKey
NSTextCheckingOrganizationKey
NSTextCheckingStreetKey
NSTextCheckingCityKey
NSTextCheckingStateKey
NSTextCheckingZIPKey
NSTextCheckingCountryKey
NSTextCheckingPhoneKey
NSTextCheckingAirlineKey
NSTextCheckingFlightKey
关于macos - 如何将地址字符串转换为地址字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23607832/