gpt4 book ai didi

ios - 哪个 NSCharacterSet 描述了在 tel : URL? 中有效的字符

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:06 25 4
gpt4 key购买 nike

接受 StringNSURL 初始化器是可失败的,文档说:

If the URL string was malformed, returns nil.

尝试使用 NSURL(string: "tel://+49 00 00 00 00 00") 构建 URL 返回 nil。

stringByAddingPercentEscapesUsingEncoding(_:) 和 friend 在 iOS 9 中被弃用,取而代之的是 stringByAddingPercentEncodingWithAllowedCharacters(_:),它采用 NSCharacterSet。哪个 NSCharacterSet 描述了 tel: URL 中有效的字符?

没有

  • URLFragmentAllowedCharacterSet()
  • URLHostAllowedCharacterSet()
  • URLPasswordAllowedCharacterSet()
  • URLPathAllowedCharacterSet()
  • URLQueryAllowedCharacterSet()
  • URLUserAllowedCharacterSet()

...似乎是相关的

最佳答案

您可以使用 NSDataDetector 类从字符串中 grep 电话号码。下一步从检测到的数字中删除所有不必要的字符并创建 NSURL。

  func getPhoneNumber(string: String) -> String? {
if let detector = try? NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue) {
let matches = detector.matchesInString(string, options: [], range: NSMakeRange(0, string.characters.count))

if let string = matches.flatMap({ return $0.phoneNumber}).first {
let number = convertStringToNumber(string)
return number
}
}


return nil
}

func convertStringToNumber(var str: String) -> String {
let set = NSMutableCharacterSet()
set.formUnionWithCharacterSet(NSCharacterSet.whitespaceCharacterSet())
set.formUnionWithCharacterSet(NSCharacterSet.symbolCharacterSet())
set.formUnionWithCharacterSet(NSCharacterSet.punctuationCharacterSet())

str = str.componentsSeparatedByCharactersInSet(set).reduce(String(), combine: +)

return str
}

示例:

 let possibleNumber = "+49 00 00 00 00 00"

if let number = getPhoneNumber(possibleNumber), let url = NSURL(string: "tel://\(number)") {
print(url.absoluteString)
}

关于ios - 哪个 NSCharacterSet 描述了在 tel : URL? 中有效的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35889628/

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