Swift - encode URL

后端 未结 17 1911
無奈伤痛
無奈伤痛 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.

提交回复
热议问题