簡體   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