gpt4 book ai didi

ios - 如何在 NSURL 中使用非英文字符串?

转载 作者:搜寻专家 更新时间:2023-10-30 23:15:04 25 4
gpt4 key购买 nike

当我在代码中使用日语时

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

最佳答案

日语字符(与任何国际字符一样)绝对是个问题。 URL 中允许的字符非常有限。如果它们出现在字符串中,则可失败的 URL 初始化程序将返回 nil。这些字符必须进行百分号转义。

如今,我们会使用 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!

有关手动百分比编码的 Swift 2 答案,请参阅 prior revision of this answer .

关于ios - 如何在 NSURL 中使用非英文字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38359709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com