Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use non-english string in NSURL?

Tags:

ios

swift

nsurl

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

like image 233
Nishad Avatar asked Oct 18 '22 05:10

Nishad


1 Answers

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.

like image 113
Rob Avatar answered Oct 21 '22 00:10

Rob