如何从带有随机文本和内部电话号码的字符串中获取电话号码URL

时间:2019-06-20 13:05:08

标签: swift nsurl uialertcontroller uiapplication nsdatadetector

在我的iOS应用程序中,我有一堆包含文本和一个嵌入式电话号码的alertController消息,我想为用户提供通过alerControllerAction进行调用的可能性,为此,我需要能够提取动态地从字符串中获取电话号码,将其转换为电话号码URL,然后让老的迅捷的家伙完成工作,这就是我在围绕NSDataDetector跟踪了数十个tuto之后所做的事情,出于某种原因,我想到了这个函数总是在我的phoneNumberURL对象中返回nil。你们可以检查一下,然后告诉我是否出现问题吗?

这里什么都没有:

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)
        }
    }

预先感谢您,加油!

2 个答案:

答案 0 :(得分:0)

您的方法似乎还可以,但我怀疑也许有关您的输入数据的某些问题才是真正的问题。尝试在操场上进行实验:

import Foundation

enum PhoneNumberDetectionError: Error {
    case nothingDetected
    case noNumberFound
}

func extractPhoneURL(from string: String) throws -> URL? {
    let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)

    guard let detected = detector.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) else {
        throw PhoneNumberDetectionError.nothingDetected
    }

    guard let number = detected.phoneNumber else {
        throw PhoneNumberDetectionError.noNumberFound
    }

    let noWhiteSpaces = number.filter { !$0.isWhitespace }

    return URL(string: "tel://\(noWhiteSpaces)")
}

let strings = [
    "This 555–692–7753 is a phone number",
    "This 1 555 692 7753 is a phone number",
    "This 123 is an incomplete phone number",
    "This does not have a phone number",
    "This +1 555 692 7753 is a phone number",
]

strings.forEach {
    do {
        guard let url = try extractPhoneURL(from: $0) else {
            print("❌ '\($0)' failed to make URL")
            return
        }
        print("✅ '\($0)' -> \(url.absoluteString)")
    } catch {
        print("❌ '\($0)' : \(error)")
    }
}

如果您认为应该有效的任何内容都获得了❌,那就是您的问题。

此外,在几个地方,您还有一些奇怪的( )

// Odd combination of optional unwrap and force-unwrap
phoneNumber = (phoneNumberDetected?.phoneNumber)!

// Concise equivalent
phoneNumber = phoneNumberDetected!.phoneNumber

并且:

// The brackets around the string concatenation don't achieve anything
if let phoneURL = NSURL(string: ("tel://" + phoneNumber))

// Better
if let phoneURL = NSURL(string: "tel://" + phoneNumber)

答案 1 :(得分:0)

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

与其尝试从消息中提取一个数字并希望它是电话号码,而不是距离或门牌号码,不如在本地化字符串中引入占位符(%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...

}