如何在NSURL中使用非英语字符串?

时间:2016-07-13 19:00:16

标签: ios swift nsurl

当我在我的代码中使用日语时

func getChannelDetails(useChannelIDParam: Bool) {
    var urlString: String!
    if !useChannelIDParam {
        urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet%2Cid&maxResults=50&order=viewCount&q=ポケモンGO&key=\(apikey)"
    }

我遇到了问题

  

致命错误:在解包可选值时意外发现nil

1 个答案:

答案 0 :(得分:3)

日文字符(就像任何国际字符一样)肯定是个问题。 URL中允许的字符非常有限。如果它们出现在字符串中,则可用的URL初始值设定项将返回nil。这些字符必须是百分比转义。

如今,我们使用URLComponents来对该网址进行百分比编码。例如:

var components = URLComponents(string: "https://www.googleapis.com/youtube/v3/search")!
components.queryItems = [
    URLQueryItem(name: "part",       value: "snippet,id"),
    URLQueryItem(name: "maxResults", value: "50"),
    URLQueryItem(name: "order",      value: "viewCount"),
    URLQueryItem(name: "q",          value: "ポケモンGO"),
    URLQueryItem(name: "key",        value: apikey)
]
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") // you need this if your query value might have + character, because URLComponents doesn't encode this like it should
let url = components.url!

对于使用手动百分比编码的Swift 2答案,请参阅prior revision of this answer