鉴于代表iOS设备上的日历条目的EKEvent,我试图不仅检测电话号码,还检测相关的电话会议访问代码。
例如,给定:
NSString *text = @"Blah Blah Blah (555) 123-4567 Access Code: 9876# Blah Blah Blah";
我想实现一个返回此值的方法:
@"555-123-4567,,9876#"
日历条目可能会使用@"Access Code: "
以外的各种文字来描述用于访问电话会议的号码。例如,其他字符串可能包含@"passcode: "
,@"virtual room number: "
等
我知道NSDataDetector能够检测到电话号码,但鉴于上面的示例字符串,它会返回@"555-123-4567 Access Code: 9876#"
(请注意'访问代码'这里仍然是一个子串。)
我正在考虑从NSDataDetector返回的值并对@"Access Code: "
以及可能出现在日历条目中的类似子字符串执行字符串替换,替换为@",,"
,但这并不是似乎足够优雅。我更喜欢NSDataDetector为我做这件事。
这是我的代码,我并不满意:
- (NSArray *) phonesFromText:(NSString *)text {
NSMutableArray *phones = [NSMutableArray array];
if (text) {
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber
error:&error];
[detector enumerateMatchesInString:text
options:kNilOptions
range:NSMakeRange(0, [text length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSString *phoneNumberWithText = result.phoneNumber;
// Replace "access code:" with ",," so that it can be dialed by the built-in phone app
NSString *phoneNumberWithoutText = [phoneNumberWithText stringByReplacingOccurrencesOfString:@"access code:"
withString:@",,"
options:NSCaseInsensitiveSearch
range:NSMakeRange(0, [phoneNumberWithText length])];
// Remove any unwanted characters that may still be lingering after the above string replacement
NSCharacterSet * toRemove = [[NSCharacterSet characterSetWithCharactersInString:@"+,#-0123456789"] invertedSet];
phoneNumberWithoutText = [[phoneNumberWithoutText componentsSeparatedByCharactersInSet:toRemove] componentsJoinedByString:@""];
[phones addObject:phoneNumberWithoutText];
}];
}
return phones;
}
问题:除了我上面提到的字符串替换解决方案之外,还有更好的方法吗?