URL构造函数不适用于某些字符 [英] URL constructor doesn't work with some characters
问题描述
我正在尝试使用URLRequest从我的应用程序调用php脚本.Url路径是在字符串变量 query
中生成的,对于请求,我将其转换为这样
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?
推荐答案
URL(string:)
初始化程序不需要将 String
编码为有效的URL String
,它假定 String
已被编码为仅包含在 URL
中有效的字符.因此,如果您的 String
包含无效的URL字符,则必须进行编码.您可以通过调用 String.addingPercentEncoding(withAllowedCharacters:)
来实现.
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 }
您可以根据URL的哪个部分包含需要编码的字符来更改 CharacterSet
,我只是出于演示目的使用 urlQueryAllowed
.
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.
这篇关于URL构造函数不适用于某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!