问题
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
guard let url = URL(string: query) else {
print("error")
return
}
usually it works, but when the request contains characters like ä, ö, ü, ß the error is triggered. How can I make it work?
回答1:
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.
回答2:
Split your URL in two separate parts:
let baseURLString = "https://www.example.com"
let pathComponent = "áűáeqw"
let fullURL = URL(string: baseURLString)?.appendingPathComponent(pathComponent)
来源:https://stackoverflow.com/questions/50466880/url-constructor-doesnt-work-with-some-characters