gpt4 book ai didi

swift - 如何从包含随机文本和电话号码的字符串中获取电话号码 URL

转载 作者:行者123 更新时间:2023-11-30 10:41:33 27 4
gpt4 key购买 nike

在我的iOS应用程序中,我有一堆包含文本和一个嵌入电话号码的alertController消息,我想为用户提供从alerControllerAction调用电话的可能性,为此我需要能够提取动态地从字符串中获取电话号码,将其转换为电话号码 URL,然后让那个敏捷的老家伙完成它的工作,这就是我在围绕 NSDataDetector 学习了大约几十个教程后所做的,我想出了这个函数,出于某种原因我的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)
}
}

预先感谢您,干杯!

最佳答案

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

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com