swift - Swift String 省略/转换波兰语重音
问题描述
我有以下问题:我正在发出 API 请求。使用城市名称 fe 'Poznań" (包含某些语言的一些典型标志),swift 不想给我结果,但是当我通过 Postman 应用程序执行相同的请求时,它会以适当的方式给出结果。怎么能我可以阻止 swift 转换那些“奇怪”的字母吗?“city.name”是我从以前的 VC 和 googlePlaces API 传递的城市名称。这是请求示例和我的部分代码: https://samples.openweathermap .org/data/2.5/weather?q=London&appid=b6907d289e10d714a6e88b30761fae22
private let kWeatherAPIURL = "https://api.openweathermap.org/data/2.5/weather?q=%@&appid=%@"
let urlString = String(format: kWeatherAPIURL, city.name, weatherAPIKey)
guard let url = URL(string: urlString) else {
print("address doesnt exist!")
return
}
解决方案
为简洁起见,我在这里强制展开:
let kWeatherAPIURL = "https://api.openweathermap.org/data/2.5/weather?q=%@&appid=%@"
let weatherAPIKey = "YourWeatherAPIKey"
let cityName = "Poznań"
let cString = cityName.cString(using: .utf8)!
let utf8CityName = cityName.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let urlString = String(format: kWeatherAPIURL, utf8CityName, weatherAPIKey)
let url = URL(string: urlString)!
//https://api.openweathermap.org/data/2.5/weather?q=Pozna%C5%84&appid=YourWeatherAPIKey
一种安全的方法是使用URL 组件:
let weatherAPIKey = "YourWeatherAPIKey"
let cityName = "Poznań"
var components = URLComponents()
components.scheme = "https"
components.host = "api.openweathermap.org"
components.path = "/data/2.5/weather"
components.queryItems = [URLQueryItem(name: "q", value: cityName),
URLQueryItem(name: "appid", value: weatherAPIKey)
]
print(components.url!) //https://api.openweathermap.org/data/2.5/weather?q=Pozna%C5%84&appid=YourWeatherAPIKey
推荐阅读
- javascript - 根据 js 条件显示刻度线或叉号
- python - 有没有办法从扮演多个角色的演员那里检索剧集计数和日期?
- python - Pip install states 模块已经下载但我不能使用它?
- java - 我在 Eclipse 中摆动时遇到问题
- google-sheets - 在单元格中选择特定文本 - Google 表格
- reactjs - 反应翻转卡
- python - 将网页抓取结果缩短为 .txt 文件
- javascript - 带有ajax的函数序列化()不返回任何内容
- sql-server - 使用 Always On 的 SQL Server 差异备份
- javascript - 在 ap 标签中显示输入而不更改字体