Swift - encode URL

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

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

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

    Swift 4 & 5 (Thanks @sumizome for suggestion. Thanks @FD_ and @derickito for testing)

    var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
    allowedQueryParamAndKey.remove(charactersIn: ";/?:@&=+$, ")
    paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
    

    Swift 3

    let allowedQueryParamAndKey =  NSCharacterSet.urlQueryAllowed.remove(charactersIn: ";/?:@&=+$, ")
    paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
    

    Swift 2.2 (Borrowing from Zaph's and correcting for url query key and parameter values)

    var allowedQueryParamAndKey =  NSCharacterSet(charactersInString: ";/?:@&=+$, ").invertedSet
    paramOrKey.stringByAddingPercentEncodingWithAllowedCharacters(allowedQueryParamAndKey)
    

    Example:

    let paramOrKey = "https://some.website.com/path/to/page.srf?a=1&b=2#top"
    paramOrKey.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey)
    // produces:
    "https%3A%2F%2Fsome.website.com%2Fpath%2Fto%2Fpage.srf%3Fa%3D1%26b%3D2%23top"
    

    This is a shorter version of Bryan Chen's answer. I'd guess that urlQueryAllowed is allowing the control characters through which is fine unless they form part of the key or value in your query string at which point they need to be escaped.

    0 讨论(0)
  • 2020-11-21 23:01

    Swift 3:

    let allowedCharacterSet = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
    
    if let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
    //do something with escaped string
    }
    
    0 讨论(0)
  • 2020-11-21 23:02

    This one is working for me.

    func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
    
        let unreserved = "*-._"
        let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
        allowed.addCharactersInString(unreserved)
    
        if plusForSpace {
            allowed.addCharactersInString(" ")
        }
    
        var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)
    
        if plusForSpace {
            encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+")
        }
        return encoded
    }
    

    I found above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/.

    0 讨论(0)
  • 2020-11-21 23:07

    You can use URLComponents to avoid having to manually percent encode your query string:

    let scheme = "https"
    let host = "www.google.com"
    let path = "/search"
    let queryItem = URLQueryItem(name: "q", value: "Formula One")
    
    
    var urlComponents = URLComponents()
    urlComponents.scheme = scheme
    urlComponents.host = host
    urlComponents.path = path
    urlComponents.queryItems = [queryItem]
    
    if let url = urlComponents.url {
        print(url)   // "https://www.google.com/search?q=Formula%20One"
    }
    

    extension URLComponents {
        init(scheme: String = "https",
             host: String = "www.google.com",
             path: String = "/search",
             queryItems: [URLQueryItem]) {
            self.init()
            self.scheme = scheme
            self.host = host
            self.path = path
            self.queryItems = queryItems
        }
    }
    

    let query = "Formula One"
    if let url = URLComponents(queryItems: [URLQueryItem(name: "q", value: query)]).url {
        print(url)  // https://www.google.com/search?q=Formula%20One
    }
    
    0 讨论(0)
  • 2020-11-21 23:09

    Swift 4.2

    A quick one line solution. Replace originalString with the String you want to encode.

    var encodedString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]{} ").inverted)
    

    Online Playground Demo

    0 讨论(0)
提交回复
热议问题