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

问题描述 投票:1回答:4

我正在尝试使用此代码使用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/,寻找旧金山也没有结果。

这里缺少什么?

ios swift weather-api openweathermap
4个回答
4
投票

您需要用+号替换城市名称中的空格

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

enter image description here如果你看地址栏 - 它用plus本身替换空格。

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

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


2
投票

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

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

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

实际上,空间支持被打破了。请用下划线替换它们。实际上,您可以省略拼写“旧金山”作为“SanFrancisco”的空格,但这种方式可能会导致一些特定城市的意外结果,“San_Francisco”是最好的形式。

因此,处理此问题的正确方法如下:

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

1
投票

尝试删除空格,所以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


0
投票

今天我遇到了同样的问题,并且能够修复如下:

city = city.split(' ').join('+');
© www.soinside.com 2019 - 2024. All rights reserved.