2016-07-13 12 views
5

私は自分のコード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)" 
    } 

で日本語を使用する場合、私は問題に直面

fatal error: unexpectedly found nil while unwrapping an Optional value

+0

有用なコメント:あなたのマテリアルを上回っている人を知っている場合は、相談してください。 – halfer

+1

だからポケモンGOもスタックオーバーフローを克服しました:-) –

+0

あなたはこれを参照することができますhttp://stackoverflow.com/questions/32064754/how-to-use-stringbyaddingpercentencodingwithallowedcharacters-for-a-url-in-swi –

答えて

3

日本語の文字は、(任意の国際文字になるように)確かに問題です。 URLで許可される文字は非常に限られています。それらが文字列に存在する場合は、URLイニシャライザはnilを返します。これらの文字はパーセントエスケープされていなければなりません。

最近では、URLComponentsを使用してそのURLをパーセントエンコードしています。たとえば:マニュアルパーセントエンコーディングスイフト2の答えを

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! 

prior revision of this answerを参照してください。

+0

'URL.init(文字列:" https://ja.wikipedia.org/wiki/カレイリス ")'が失敗する: - /これはAppleの完璧なURLです。 – Jonny

+1

さて、技術的にはそうではありません。 Webブラウザは、このようにすべてのコードをこのように効率的にエンコーディングしています。有効であると思われますが、たとえばSafari Web Inspectorを使用すると、実際にはURLが['https:// ja.wikipedia.org/wiki/%E3%82%AB%E3%83%AC%E3%83%BC%E3%83%A9%E3%82%A4%E3%82%B9'](https:/ /ja.wikipedia.org/wiki/%E3%82%AB%E3%83%AC%E3%83%BC%E3%83%A9%E3%82%A4%E3%82%B9)。 – Rob

+0

幸運。頑張ってください – Rob