所以,我有一个应用程序,您在其中引入UITextField
中的文本,然后执行带有文本的Alamofire .GET
请求。有时,该文本是用Chinese, Korean, Japanese
编写的......而Alamofire崩溃,但是如果我在浏览器中输入带有中文字符的URL,它就会完美地返回。
这是网址:
https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,snippet(title,channelTitle,thumbnails))&order=viewCount&q=不許你注定一人&type=video&maxResults=50&key=Whatever
如您所见,它包含中文文本:
不許你注定一人
这就是Alamofire .GET请求:
let url = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(Text)&type=video&maxResults=50&key=Whatever"
let nUrl = url.replacingOccurrences(of: " ", with: "+")
Alamofire.request(nUrl, method: .get).validate().responseJSON { response in
谢谢!
答案 0 :(得分:1)
您是否尝试在RFC 3986之后对网址进行编码?
extension String {
func stringByAddingPercentEncodingForRFC3986() -> String? {
let unreserved = "-._~/?"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
return self.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
}
}
<强>用法强>:
let nUrl = url.stringByAddingPercentEncodingForRFC3986()