How to convert an address string to an address dictionary

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 04:01:14

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/23607832/how-to-convert-an-address-string-to-an-address-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!