在我的 iOS 应用程序中,我有一堆包含文本和一个嵌入式电话号码的 alertController 消息,我想为用户提供从 alerControllerAction 拨打电话的可能性,为此我需要能够提取电话号码动态地从字符串中,将其转换为电话号码 URL 并让老 swift 家伙完成它的工作,这就是我在围绕 NSDataDetector 跟随大约十几个 tuto 之后所做的,我想出了这个函数,由于某种原因总是返回 nil在我的 phoneNumberURL 对象中。你们能检查一下并告诉我是否有什么不对劲吗?
这里什么都没有:
private func showsHelpMessage()
{
let title = Bundle.main.localizedString(forKey: "account.help.popup.title",
value: "",
table: AFPConfig.sharedInstance.kLocalizableTable)
let message = Bundle.main.localizedString(forKey: "account.help.popup.message",
value: "",
table: AFPConfig.sharedInstance.kLocalizableTable)
var phoneNumber : String = ""
let detectorType: NSTextCheckingResult.CheckingType = [.phoneNumber]
do
{
let detector = try NSDataDetector(types: detectorType.rawValue)
let phoneNumberDetected = detector.firstMatch(in: message, options: [], range: NSRange(location: 0, length: message.utf16.count))
phoneNumber = (phoneNumberDetected?.phoneNumber)!
phoneNumber = phoneNumber.removeWhitespace() // added this because i noticed the NSURL kept crashing because of the whitespaces between numbers
}
catch
{
phoneNumber = "+33969390215"
}
if let phoneURL = NSURL(string: ("tel://" + phoneNumber))
{
let alertAccessibility = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alertAccessibility.addAction(UIAlertAction(title: "Appeler ?", style: .destructive, handler: { (action) in
UIApplication.shared.open(phoneURL as URL, options: [:], completionHandler: nil)
}))
alertAccessibility.addAction(UIAlertAction(title: "Annuler", style: UIAlertAction.Style.cancel, handler: nil))
self.present(alertAccessibility, animated: true, completion: nil)
}
}
提前谢谢你,干杯!