URL constructor doesn't work with some characters

后端 未结 2 754
余生分开走
余生分开走 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:29

    Split your URL in two separate parts:

    let baseURLString = "https://www.example.com"
    let pathComponent = "áűáeqw"
    let fullURL = URL(string: baseURLString)?.appendingPathComponent(pathComponent)
    
    0 讨论(0)
  • 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.

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