非拉丁字符Alamofire 4.0。获取请求

时间:2016-10-26 10:33:35

标签: ios swift alamofire

所以,我有一个应用程序,您在其中引入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

谢谢!

1 个答案:

答案 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()