Search code examples
iosobjective-curlnsdatadetector

Can not analyse url in NSString when this string contains chinese by NSDataDetector


There have no match ====================================================

I know, it's the problem of "blank space", if I add blank at the front of "https", then it works. So NSDataDetector can not solve this problem?

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];
    }  
}

Solution

  • This is a known issue with NSDataDetector that if there is a space before the protocol i.e. http:// or https:// then it works, otherwise it doesn't.

    For e.g.

        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)
    }
    

    Output: https://www.sharpkits.com

    and for let input = "This is a test with the URLhttps://www.sharpkits.com to be detected."

    Output: URLhttps://www.sharpkits.com

    So nope can't be done with NSDataDetector