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

时间:2016-03-09 10:57:49

标签: ios nsstring ios9 tel

NSURL的{​​{1}}初始化程序可以使用,文档说:

  

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

尝试构建一个String的网址,返回nil。

NSURL(string: "tel://+49 00 00 00 00 00")和朋友在iOS 9中被弃用,而stringByAddingPercentEscapesUsingEncoding(_:)则需要stringByAddingPercentEncodingWithAllowedCharacters(_:)。哪个NSCharacterSet描述了NSCharacterSet网址中有效的字符?

没有

  • tel:
  • URLFragmentAllowedCharacterSet()
  • URLHostAllowedCharacterSet()
  • URLPasswordAllowedCharacterSet()
  • URLPathAllowedCharacterSet()
  • URLQueryAllowedCharacterSet()

......似乎是相关的

1 个答案:

答案 0 :(得分:0)

您可以 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)
 }