这个答案基本上建立在Kamil.S 的原则上,但使用现代API,如果拼写错误,它根本不会打开phoneUrl。它还可以防止在电话号码中重复输入+。
在研究如何正确拨打电话时,发现只有容易出错的电话号码检测还试图在没有第三方依赖的情况下进行更好的检测。 (请注意,以下解决方案并不意味着扫描整个文本,可能有很多数字散布在单词之间)
PS:但是是的,当数字的排序有意义时,您甚至可以将电话号码隐藏在更大的字符串中。假设你有一个 NSString *dirty; 包含..
@"uglyPreString +49(17)-12-+345-678 uglyPostString seePlusInBetween?"
或@"tel://+49(17)-12-+345-678"
它会起作用吗?
决定编写一个确保您在发送电话号码以调用其他应用程序(即电话应用程序)之前拥有正确的可拨号号码。
NSString *dirty = @"uglyPreString +49(017)-12-+345-678 uglyPostString seePlusInBetween?";
// Let's keep all (only) possible phone number parts with a regex.
dirty = [dirty stringByReplacingOccurrencesOfString:@"[^0-9,^+]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, dirty.length)];
// We may have doublet '+' sign in there
// ending up in a wrong call, prevent that
if (dirty.length>1) {
// If the possible string contains '+' twice, kick out all '+' after first.
// If there was no + sign at all, string stays as is. And
// do not exceed max character index = NSMakeRange(1, dirty.length-1)
dirty = [dirty stringByReplacingOccurrencesOfString:@"[+]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(1, dirty.length-1)];
NSLog(@"does it look nice here? phone: %@",dirty);
}
// make sure it will not validate if detector doesnt agree its a phonenumber
// we don't want phonenumbers to fly as url call between app without users consent
// only apps that conform to handle @"tel://" protocol should be able to handle your call.
// so we set phonenumber invalid first.
NSString *phonenumber = nil;
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
NSArray *check = [detector matchesInString:dirty options:0 range:NSMakeRange(0, dirty.length)];
if (check) {
for (NSTextCheckingResult *result in check) {
phonenumber = [result phoneNumber];
if (phonenumber) break;
}
// if this part is reached, there is no valid phonenumber in dirty
}
if (phonenumber) {
// construct the phone url
NSString *dial = [NSString stringWithFormat:@"tel://%@",phonenumber];
NSURL *phoneUrl = [NSURL URLWithString:dial];
NSLog(@"dial will be %@",phoneUrl.absoluteString);
if ([UIApplication.sharedApplication canOpenURL:phoneUrl]) {
[UIApplication.sharedApplication openURL:phoneUrl options:@{} completionHandler:^(BOOL success) {
// assuming the app that opens is phone app.
NSLog(@"pressed %@ button", success ? @"green/call" : @"red/cancel");
}];
}
}