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

Nis*_*had 5 nsurl ios swift

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

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)"
    }
Run Code Online (Sandbox Code Playgroud)

我遇到了问题

致命错误:在展开Optional值时意外发现nil

Rob*_*Rob 3

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

\n\n

如今,我们会URLComponents对该 URL 进行百分比编码。例如:

\n\n
var components = URLComponents(string: "https://www.googleapis.com/youtube/v3/search")!\ncomponents.queryItems = [\n    URLQueryItem(name: "part",       value: "snippet,id"),\n    URLQueryItem(name: "maxResults", value: "50"),\n    URLQueryItem(name: "order",      value: "viewCount"),\n    URLQueryItem(name: "q",          value: "\xe3\x83\x9d\xe3\x82\xb1\xe3\x83\xa2\xe3\x83\xb3GO"),\n    URLQueryItem(name: "key",        value: apikey)\n]\ncomponents.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\nlet url = components.url!\n
Run Code Online (Sandbox Code Playgroud)\n\n

对于使用手动百分比编码的 Swift 2 答案,请参阅此答案的先前修订版

\n