I extract addresses from text using OSX data detectors. This gives me address strings like “1 Infinite Loop, Cupertino, CA”.
In order to put such addresses into the OSX address book, I have to convert them to a dictionary with keys like "Street", "City", "Country" etc.
I know that there is a function that does the reverse: ABCreateStringWithAddressDictionary(...)
, but I need it the other way.
The only way I know this can be done (and is, of course, total overkill) is to send the address string to a CLGeocoder
, which returns the coordinates of the address, and send then the coordinates again for reverse geocoding, which returns a placemark containing the address dictionary.
There must be an easier way to do this.
EDIT:
I learned by now,
1) that this problem is really complicated, and is really done best by using a geocoding server, see e.g. here,
2) that it is enough to contact the geocoding server only once: When an address string is sent there, an address directory is sent back.
How to convert an address string to an address dictionary
Asked Answered
If you are using a data detector with type NSTextCheckingTypeAddress
, the returned matches should provide an addressComponents dictionary.
That dictionary contains all the keys you mentioned.
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);
}
}
The above snippet returns the following for the input string:
Address Dictionary:{
City = Cupertino;
State = CA;
Street = "1 Infinite Loop";
}
A fully featured address string would result in values for the following keys:
NSTextCheckingNameKey
NSTextCheckingJobTitleKey
NSTextCheckingOrganizationKey
NSTextCheckingStreetKey
NSTextCheckingCityKey
NSTextCheckingStateKey
NSTextCheckingZIPKey
NSTextCheckingCountryKey
NSTextCheckingPhoneKey
NSTextCheckingAirlineKey
NSTextCheckingFlightKey
© 2022 - 2024 — McMap. All rights reserved.