繁体   English   中英

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

[英]Which NSCharacterSet describes characters which are valid in a tel: URL?

使用StringNSURL初始化程序是失败的,并且文档说:

如果URL字符串格式错误,则返回nil。

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

stringByAddingPercentEscapesUsingEncoding(_:)和朋友支持已弃用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)
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM