Swift - encode URL

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

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  暖寄归人
    2020-11-21 22:53

    What helped me was that I created a separate NSCharacterSet and used it on an UTF-8 encoded string i.e. textToEncode to generate the required result:

    var queryCharSet = NSCharacterSet.urlQueryAllowed
    queryCharSet.remove(charactersIn: "+&?,:;@+=$*()")
        
    let utfedCharacterSet = String(utf8String: textToEncode.cString(using: .utf8)!)!
    let encodedStr = utfedCharacterSet.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
        
    let paramUrl = "https://api.abc.eu/api/search?device=true&query=\(escapedStr)"
    

提交回复
热议问题