NSDataDetector does not find phone number type

I am trying to convert this Objective-C working code to Swift ( which is based on this Apple documentation )

-(BOOL)validatePhone:(NSString*)phone {
    NSError *error = NULL;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
                                                               error:&error];

    NSArray *matches = [detector matchesInString:phone
                                         options:0
                                           range:NSMakeRange(0, [phone length])];

    for (NSTextCheckingResult *match in matches) {
        if ([match resultType] == NSTextCheckingTypePhoneNumber) {
            NSString *phoneNumber = [match phoneNumber];
            self.inputPhoneNumber.text = phoneNumber;
            return TRUE;
        }
    }
    NSLog(@"Phone Number Not Found");
    return FALSE;
}

Here is my quick conversion:

func validatePhone(phone: NSString) -> Bool {
    var error: NSError?
    let detector = NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue, error: &error)

    var matches: NSArray = [detector!.matchesInString(phone as String, options: nil, range: NSMakeRange(0, phone.length))]

    var match:NSTextCheckingResult

    for match in matches{
        if match.resultType == NSTextCheckingType.PhoneNumber{
            inputPhoneNumber.text = match.phoneNumber
            return true
        }
    }

    NSLog("Phone Number Not Found")

    return false
}

The array matchescorrectly matches the entered phone number and correctly displays the type, as shown below:

enter image description here

But my operator ifalways returns false when checking the type of result

if match.resultType == NSTextCheckingType.PhoneNumber

Entrance tested as 555-555-5555 or 5558881234

So, how should I check for NSTextCheckingType correctly?

+4
source share
1 answer

Try the following:

var text = "555-555-5555"

let types: NSTextCheckingType = .PhoneNumber
var error : NSError?

let detector = NSDataDetector(types: types.rawValue, error: &error)
var matches = detector!.matchesInString(text, options: nil, range: NSMakeRange(0, count(text)))

for match in matches {
   println(match.phoneNumber!)
}

resultType, , .

, , , :

var text = "http://www.example.com"

let types: NSTextCheckingType = .PhoneNumber | .Link
var error : NSError?

let detector = NSDataDetector(types: types.rawValue, error: &error)
var matches = detector!.matchesInString(text, options: nil, range: NSMakeRange(0, count(text)))

, , :

for match in matches {
    if let phone = match.phoneNumber! {
        println(phone)
    }

    if let url = match.URL! {
       println(url)
    }
}

, .

+2

All Articles