2016-10-26 183 views
2

因此,我有一個應用程序在其中引入了一個文本UITextField,然後它執行一個帶有文本的Alamofire .GET請求。有時,該文本是寫在Chinese, Korean, Japanese ......而Alamofire崩潰,但是,如果我在瀏覽器中輸入中文字符的URL,它會完美返回。非拉丁字符Alamofire 4.0 .GET請求

這是網址:

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不用彷徨要求:

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

你試過編碼你的url後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() 
+0

工作!非常感謝! – ctabuyo