So, I have an App in which you introduce a text in a UITextField and then it performs an Alamofire .GET request with text. Sometimes, that text is written in Chinese, Korean, Japanese... And Alamofire crashes, however if I type the URL in the browser with the Chinese characters it returns perfectly.
This is the 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
As you can see it contains the Chinese text:
不許你注定一人
And this is the Alamofire .GET request:
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
Thanks!
Have you try to encode your url following RFC 3986 ?
extension String {
func stringByAddingPercentEncodingForRFC3986() -> String? {
let unreserved = "-._~/?"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
return self.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
}
}
Usage:
let nUrl = url.stringByAddingPercentEncodingForRFC3986()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With