Swift - encode URL

后端 未结 17 1872
無奈伤痛
無奈伤痛 2020-11-21 22:20

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  执笔经年
    2020-11-21 22:45

    Swift 3

    In Swift 3 there is addingPercentEncoding

    let originalString = "test/test"
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    print(escapedString!)
    

    Output:

    test%2Ftest

    Swift 1

    In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

    var originalString = "test/test"
    var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
    println("escapedString: \(escapedString)")
    

    Output:

    test%2Ftest

    The following are useful (inverted) character sets:

    URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
    URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
    URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
    URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
    URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
    URLUserAllowedCharacterSet      "#%/:<>?@[\]^`
    

    If you want a different set of characters to be escaped create a set:
    Example with added "=" character:

    var originalString = "test/test=42"
    var customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
    var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
    println("escapedString: \(escapedString)")
    

    Output:

    test%2Ftest%3D42

    Example to verify ascii characters not in the set:

    func printCharactersInSet(set: NSCharacterSet) {
        var characters = ""
        let iSet = set.invertedSet
        for i: UInt32 in 32..<127 {
            let c = Character(UnicodeScalar(i))
            if iSet.longCharacterIsMember(i) {
                characters = characters + String(c)
            }
        }
        print("characters not in set: \'\(characters)\'")
    }
    

提交回复
热议问题