When I use Japanese language at my code
当我在我的代码中使用日语时
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)"
}
I face the problem
我遇到了问题
fatal error: unexpectedly found nil while unwrapping an Optional value
致命错误:在展开Optional值时意外发现nil
1 个解决方案
#1
3
The Japanese characters (as would be any international characters) definitely are a problem. The characters allowed in URLs are quite limited. If they are present in the string, the failable URL
initializer will return nil
. These characters must be percent-escaped.
日文字符(就像任何国际字符一样)肯定是个问题。 URL中允许的字符非常有限。如果它们出现在字符串中,则可用的URL初始值设定项将返回nil。这些字符必须进行百分比转义。
Nowadays, we'd use URLComponents
to percent encode that URL. For example:
如今,我们使用URLComponents对该URL进行百分比编码。例如:
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!
For Swift 2 answer with manual percent encoding, see prior revision of this answer.
对于手动百分比编码的Swift 2答案,请参阅此答案的先前修订版。
#1
3
The Japanese characters (as would be any international characters) definitely are a problem. The characters allowed in URLs are quite limited. If they are present in the string, the failable URL
initializer will return nil
. These characters must be percent-escaped.
日文字符(就像任何国际字符一样)肯定是个问题。 URL中允许的字符非常有限。如果它们出现在字符串中,则可用的URL初始值设定项将返回nil。这些字符必须进行百分比转义。
Nowadays, we'd use URLComponents
to percent encode that URL. For example:
如今,我们使用URLComponents对该URL进行百分比编码。例如:
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!
For Swift 2 answer with manual percent encoding, see prior revision of this answer.
对于手动百分比编码的Swift 2答案,请参阅此答案的先前修订版。