简体   繁体   English

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

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

The NSURL initializer that takes a String is failable, and the documentation says: 使用StringNSURL初始化程序是失败的,并且文档说:

If the URL string was malformed, returns nil. 如果URL字符串格式错误,则返回nil。

Attempting to construct a URL with NSURL(string: "tel://+49 00 00 00 00 00") returns nil. 尝试使用NSURL(string: "tel://+49 00 00 00 00 00")构造URL会返回nil。

stringByAddingPercentEscapesUsingEncoding(_:) and friends are deprecated in iOS 9 in favour of stringByAddingPercentEncodingWithAllowedCharacters(_:) , which takes an NSCharacterSet . stringByAddingPercentEscapesUsingEncoding(_:)和朋友支持已弃用iOS中9 stringByAddingPercentEncodingWithAllowedCharacters(_:) ,这需要一个NSCharacterSet Which NSCharacterSet describes the characters which are valid in a tel: URL? 哪个NSCharacterSet描述了在tel: URL中有效的字符?

None of 没有

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

... seem to be relevant ...似乎很重要

You can NSDataDetector class to grep phone number from string. 您可以使用NSDataDetector类从字符串中获取grep电话号码。 Next step in to remove all unnecessary characters from detected number and create NSURL. 下一步是从检测到的数字中删除所有不必要的字符并创建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
    }

Example: 例:

 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