【问题标题】:Get the weather for cities with names that contain spaces using Openweathermap使用 Openweathermap 获取名称中包含空格的城市的天气
【发布时间】:2016-12-16 18:38:45
【问题描述】:

我正在尝试使用 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 也没有结果。

这里缺少什么?

【问题讨论】:

    标签: ios swift weather-api openweathermap


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

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

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

      【讨论】:

        【解决方案3】:

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

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

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

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

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

        【讨论】:

        • 我用过return containsPlacemark.locality?.replacingOccurrences(of: " ", with: ""),比较干净
        • 是的,但是当想法是用“+”替换时,你正在用空格替换
        • 您必须删除空格,如果您尝试使用 + 则没有结果。
        • 当我搜索“旧金山”时,当我搜索“旧金山”时,我得到“未找到”,我得到来自哥伦比亚和阿根廷的 SF,但不是来自美国。有什么想法吗?
        • @jreft56 你需要输入“旧金山,美国”它对我有用。他们在这三年中改变了 API :)
        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2021-10-07
          • 1970-01-01
          • 1970-01-01
          • 2021-06-17
          • 2012-11-25
          • 1970-01-01
          • 2021-07-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多