在我的iOS应用程序中,我有一堆包含文本和一个嵌入式电话号码的alertController消息,我想为用户提供通过alerControllerAction进行呼叫的可能性,为此,我需要能够提取电话号码从字符串中动态地将其转换为电话号码URL,然后让老的迅捷的家伙完成其工作,这就是我在围绕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)
        }
    }


预先感谢您,并加油!

最佳答案

解决提取无法识别为绝对电话号码的号码的问题(请参阅我的其他答案的评论):

与其尝试从消息中提取一个数字并希望它是电话号码,而不是距离或房屋号码,不如在本地化字符串中引入占位符(%d)并将电话号码插入消息中:

enum LocalPhoneNumbers {
    case reception = 1000
    case helpdesk = 4567
    // etc.
}

private function showHelpMessage() {
    // "Call the helpdesk on %d"
    let format = Bundle.main.localizedString(forKey: "account.help.popup.message",
                                              value: "",
                                              table: AFPConfig.sharedInstance.kLocalizableTable)

    let number = LocalPhoneNumbers.helpdesk.rawValue
    let message = String(format: format, number)
    let url = URL(string: "tel://\(number)")

    // Code to show alert here...

}

关于swift - 如何从带有随机文本和内部电话号码的字符串中获取电话号码URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56686641/

10-13 04:34