首页 > 解决方案 > 在Objective-C中使用DataDetector将NSTextCheckingResult addressComponents字典转换为字符串

问题描述

苹果NSDataDetector可以将地址、日期和 url 等各种东西检测为NSTextCheckingResults. 对于地址,它在字典中捕获信息,其中包含许多表示地址元素的键,例如地址、城市、州和邮政编码。 这是各种键。

我的问题是我在使用字典方面很弱,并且无法弄清楚将字典转换回常规字符串的语法。我需要一个字符串,以便将其输入到地图的自然语言查询中。

任何人都可以建议将字典转换为字符串的语法。

这是我用来检测字典的代码。

 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  
        }

    }

标签: iosobjective-cnsdictionary

解决方案


NSTextCheckingResult有一个range可以使用的属性:

这应该可以解决问题:

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

如果你想从字典中检索 if: addrDict[NSTextCheckingZIPKey]will give you 94103, addrDict[NSTextCheckingStateKey]will give youCA等,你必须重建它,但顺序取决于你。


推荐阅读