Swift - encode URL

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

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

相关标签:
17条回答
  • 2020-11-21 22:44

    None of these answers worked for me. Our app was crashing when a url contained non-English characters.

     let unreserved = "-._~/?%$!:"
     let allowed = NSMutableCharacterSet.alphanumeric()
         allowed.addCharacters(in: unreserved)
    
     let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
    

    Depending on the parameters of what you are trying to do, you may want to just create your own character set. The above allows for english characters, and -._~/?%$!:

    0 讨论(0)
  • 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)\'")
    }
    
    0 讨论(0)
  • 2020-11-21 22:45

    Swift 4:

    It depends by the encoding rules followed by your server.

    Apple offer this class method, but it don't report wich kind of RCF protocol it follows.

    var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    

    Following this useful tool you should guarantee the encoding of these chars for your parameters:

    • $ (Dollar Sign) becomes %24
    • & (Ampersand) becomes %26
    • + (Plus) becomes %2B
    • , (Comma) becomes %2C
    • : (Colon) becomes %3A
    • ; (Semi-Colon) becomes %3B
    • = (Equals) becomes %3D
    • ? (Question Mark) becomes %3F
    • @ (Commercial A / At) becomes %40

    In other words, speaking about URL encoding, you should following the RFC 1738 protocol.

    And Swift don't cover the encoding of the + char for example, but it works well with these three @ : ? chars.

    So, to correctly encoding each your parameter , the .urlHostAllowed option is not enough, you should add also the special chars as for example:

    encodedParameter = parameter.replacingOccurrences(of: "+", with: "%2B")
    

    Hope this helps someone who become crazy to search these informations.

    0 讨论(0)
  • 2020-11-21 22:46

    Everything is same

    var str = CFURLCreateStringByAddingPercentEscapes(
        nil,
        "test/test",
        nil,
        "!*'();:@&=+$,/?%#[]",
        CFStringBuiltInEncodings.UTF8.rawValue
    )
    
    // test%2Ftest
    
    0 讨论(0)
  • 2020-11-21 22:48

    let Url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")

    0 讨论(0)
  • 2020-11-21 22:49

    Swift 3:

    let originalString = "http://www.ihtc.cc?name=htc&title=iOS开发工程师"
    

    1. encodingQuery:

    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    

    result:

    "http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88" 
    

    2. encodingURL:

    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    

    result:

    "http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
    
    0 讨论(0)
提交回复
热议问题