NSDataDetector detecting “phone number” text

后端 未结 1 1211
不思量自难忘°
不思量自难忘° 2021-01-11 19:42

The easiest way I can explain this problem is with a code sample and its output, but essentially what\'s happening is NSDataDetector is detecting a phone number

相关标签:
1条回答
  • 2021-01-11 19:56

    While it does seem that this is a bug in Apple's code, there is a simple workaround if you want to extract just the number from the string by eliminating the non-numeric characters within a block:

    NSError *error = nil;
        NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
                                                                       error:&error];
    
        NSArray *stringsToTest = @[
                                    @"testing phone number 0123 4567891",
                                    @"testing some other number 0123 4567892",
                                    @"phone number 0123 4567893",
                                    @"blah blah 0123 4567894",
                                    @"testing telephone number 0123 4567895",
                                    @"phone",
                                    @"number",
                                    @"my phone number 1234587985",
                                    @"this string does not contain a phone number"
                                   ];
    
        for (NSString *string in stringsToTest)
        {
            [dataDetector enumerateMatchesInString:string
                                           options:0
                                             range:NSMakeRange(0, string.length)
                                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) 
                                        {
                                            NSString *numberWithExtra = result.phoneNumber;
                                            NSCharacterSet *toRemove = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
                                            NSString *trimmed = [[numberWithExtra componentsSeparatedByCharactersInSet:toRemove] componentsJoinedByString:@""];
                                            if(trimmed && trimmed.length)
                                            {
                                                NSLog(@"%@", trimmed);
                                            }
                                            else
                                            {
                                                NSLog(@"No phone number");
                                            }
                                        }];
        }
    
    0 讨论(0)
提交回复
热议问题