URL constructor doesn't work with some characters

后端 未结 2 781
余生分开走
余生分开走 2021-01-27 21:02

I\'m trying to call a php-script from my app using URLRequest. The Url path is generated in the String-Variable query and for the request I convert it like this

2条回答
  •  温柔的废话
    2021-01-27 21:43

    The URL(string:) initializer doesn't take care of encoding the String to be a valid URL String, it assumes that the String is already encoded to only contain characters that are valid in a URL. Hence, you have to do the encoding if your String contains non-valid URL characters. You can achieve this by calling String.addingPercentEncoding(withAllowedCharacters:).

    let unencodedUrlString = "áűáeqw"
    guard let encodedUrlString = unencodedUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: encodedUrlString) else { return }
    

    You can change the CharacterSet depending on what part of your URL contains the characters that need encoding, I just used urlQueryAllowed for presentation purposes.

提交回复
热议问题