首页 > 解决方案 > 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
    }

标签: swifturl

解决方案


为简洁起见,我在这里强制展开:

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

推荐阅读