Search code examples
iosobjective-cnsdictionary

Convert NSTextCheckingResult addressComponents dictionary to string with DataDetector in Objective-C


Apples NSDataDetector can detect a variety of things such as addresses, dates and urls as NSTextCheckingResults. For addresses, it captures the information in a dictionary with a lot of keys representing elements of the address such as address, city, state and zipcode. Here are the various keys.

My problem is that I am weak on using dictionaries and can't figure out syntax to convert the dictionary back into a regular string. I need a string so I can feed it into a natural language query for maps.

Can anyone suggest the syntax to convert the dictionary into a string.

Here is the code I am using to detect the dictionary.

 NSDictionary* addrDict= nil;
    NSString *addr = nil;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeAddress error:&error];

    NSArray *matches = [detector matchesInString:string
                                         options:0
                                           range:NSMakeRange(0, [string length])];

    NSLocale* currentLoc = [NSLocale currentLocale];

    for (NSTextCheckingResult *match in matches) {
        if ([match resultType] == NSTextCheckingTypeAddress) {

            addrDict = [match addressComponents];
//How do I convert this dictionary back into a string that says something like 
         Starbucks 123 Main Street Mountain View CA 94103  
        }

    }

Solution

  • NSTextCheckingResult has a property range that you can use:

    This should do the trick:

    NSRange addressMatchRange = [match range];
    NSString *matchString = [string substringWithRange:addressMatchRange];
    

    If you want to retrieve if from the dictionary: addrDict[NSTextCheckingZIPKey] will give you 94103, addrDict[NSTextCheckingStateKey] will give you CA, etc, and you have to reconstruct it, but the order is up to you then.