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

标签 ios nsstring ios9 tel

接受 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/

相关文章:

ios - cell.accessoryType = UITableViewCellAccessoryDe​​tailButton 接下来是什么?

ios - 将 NSString 分配给 UILabel 文本时的内存优化

ios - 无法使用两个 # 或更多将 NSString 解析为 NSURL

swift - 如何在viewDidappear之前等待函数结束?

ios - 为什么数字键盘会这样做(iOS 9)?

ios - 如何调试AudioServicesCreateSystemSoundID返回的错误-1500?

ios - Xcode 对成员 'init' 的模糊引用

ios - 使用 addChildViewController 时 IBAction 不起作用

ios - 如何在 iOS 中查找字符串并替换它的子字符串?

ios - Swift 2.0 ContactsUI 框架