当此字符串包含NSDataDetector的中文时,无法分析NSString中的url

时间:2016-10-11 05:22:36

标签: ios objective-c url nsdatadetector

没有匹配=========================================== =========

我知道,这是“空白”的问题,如果我在“https”的前面添加空白,那么它可以工作。那么NSDataDetector无法解决这个问题?

NSString *originString = @"【mans】下单立减5.00元https://kdt.im/uYMI4r";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches1 = [linkDetector matchesInString:originString options:0 range:NSMakeRange(0, [originString length])];

for (NSTextCheckingResult *match in matches1) {
    if ([match resultType] == NSTextCheckingTypeLink) {
        NSURL *url = [match URL];
    }  
}

1 个答案:

答案 0 :(得分:2)

这是NSDataDetector的一个已知问题,如果协议之前有空格,即http://或https://那么它可以正常工作,否则它就不会。

例如

    let input = "This is a test with the URL https://www.sharpkits.com to be detected."
    let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
    let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))

for match in matches {
    let url = (input as NSString).substring(with: match.range)
    print(url)
}

输出: https://www.sharpkits.com

并且对于let input ="这是一个测试,要检测URLhttps://www.sharpkits.com。"

输出:URLhttps://www.sharpkits.com

所以不能用NSDataDetector

完成任务