使用NSDataDetector在Swift(iOS)中检测并打开邮政地址

时间:2016-04-25 10:24:33

标签: ios swift nsdatadetector

我目前有一个带有地址检测功能的UITextView,它会检测此字段中的所有地址,并将它们变成一个可点击的链接,以地址为焦点打开Apple Maps。我真的很喜欢这个功能,但我的用户宁愿点击按钮而不是内联链接。 考虑到这一点,我已经研究过NSDataDetector并设法使这个功能适用于电子邮件和电话号码,但我被困在地址上。我用来检测地址的代码如下:

    let types: NSTextCheckingType = [.Address]
    let detector = try! NSDataDetector(types: types.rawValue)
    let matches = detector.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))
    for match in matches {
        return NSURL(string: "\((input as NSString).substringWithRange(match.range))")
    }

然而NSURL无法创建,我相信语法必定是错误的,它适用于以下电话号码:

    let types: NSTextCheckingType = [.PhoneNumber]
    let detector = try! NSDataDetector(types: types.rawValue)
    let matches = detector.matchesInString(input, options: [], range: NSMakeRange(0, input.characters.count))
    for match in matches {
        return NSURL(string: "telprompt://\((input as NSString).substringWithRange(match.range))")
    }

如果地址有效,则返回匹配对象中地址(街道,城市等)的组成部分。我希望NSURL可以像电话号码一样使用地址,但我可能错了,所以有另一种方法可以使用探测器的结果并手动将它们显示在Apple地图上吗?

或者作为旁注,我可以隐藏UITextView并根据按钮触摸以编程方式触发链接触摸吗?

可根据需要提供更多信息, 提前感谢您的帮助。

0 个答案:

没有答案