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
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.
Nowadays, we'd use URLComponents
to percent encode that URL. For example:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With