Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-latin characters Alamofire 4.0 .GET Request

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!

like image 441
CTABUYO Avatar asked Jan 28 '26 13:01

CTABUYO


1 Answers

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()
like image 67
Alessandro Ornano Avatar answered Jan 30 '26 06:01

Alessandro Ornano