我有以下问题: 我正在发出API请求。带有城市名称“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
}
答案 0 :(得分:2)
为了简洁起见,我被迫在这里展开:
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 components:
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
答案 1 :(得分:1)
使用URLComponents
的示例。
准备这样的功能:
func createWeatherAPIURL(cityName: String, apiKey: String) -> URL? {
let kWeatherAPIURL = "https://api.openweathermap.org/data/2.5/weather"
var urlCompo = URLComponents(string: kWeatherAPIURL)
urlCompo?.queryItems = [
URLQueryItem(name: "q", value: cityName),
URLQueryItem(name: "appid", value: apiKey)
]
return urlCompo?.url
}
并使用它:
guard let url = createWeatherAPIURL(cityName: city.name, apiKey: weatherAPIKey) else {
print("address doesnt exist!")
return
}