使用 Openweathermap 获取名称中包含空格的城市的天气

Get the weather for cities with names that contain spaces using Openweathermap

我正在尝试使用以下代码获取使用 Openweathermap 的城市的天气:

func getWeatherByCity(city: String) {
    if let weatherRequestURL = NSURL(string: "\(openWeatherMapBaseURL)?APPID=\(openWeatherMapAPIKey)&q=\(city)") {
        getWeather(weatherRequestURL: weatherRequestURL)
    }
}

(完整教程http://www.globalnerdy.com/2016/04/02/how-to-build-an-ios-weather-app-in-swift-part-1-a-very-bare-bones-weather-app/

api 适用于不包含空格的城市名称。

即使在主页 http://openweathermap.org/ 上,查找 san francisco 也没有结果。

这里缺少什么?

尝试删除 space,因此 San Francisco 变为 SanFrancisco。在 http://openweathermap.org/ 中有效。

您可以查看此线程: https://openweathermap.desk.com/customer/portal/questions/16280015-my-city-shows-up-as-http-openweathermap-org-city-?t=535697

您需要将城市名称中的空格替换为 + 符号

let string = "San Francisco"
let replaced = (string as NSString).stringByReplacingOccurrencesOfString(" ", withString: "+")

如果您查看地址栏 - 它会用加号本身替换空格。

对于这个网站,我们需要删除空格:

不确定他们为什么声称他们的搜索引擎非常灵活 :)

按照@SaintThread 的建议,删除空格是通过用空字符串替换出现的空格来完成的:

containsPlacemark.locality?.replacingOccurrences(of: " ", with: "")

但在联系支持团队后,他们建议使用下划线而不是空格。以下是他们电子邮件的摘录:

Indeed, spaces support is broken. Please just replace them with underscores. Indeed, you can just omit spaces spelling “San Francisco” as “SanFrancisco” but this manner can cause unexpected results with some particular cities, “San_Francisco” is the best form.

所以正确的处理方法如下:

containsPlacemark.locality?.replacingOccurrences(of: " ", with: "_")

今天我遇到了同样的问题,并且能够按如下方式解决它:

city = city.split(' ').join('+');