【发布时间】:2015-07-10 01:38:28
【问题描述】:
在我的一个应用程序中,我需要添加一个按城市名称查找城市的功能。我正在使用CLGeocoder 来实现这一点,并且我希望它具有与 iOS 天气应用程序相同的行为。
下面是我的代码:
CLGeocoder().geocodeAddressString(searchBar.text!, completionHandler:{ (placemarks, error) -> Void in
guard let nonNilMarks = placemarks else {return}
for placemark in nonNilMarks {
print("locality: \(placemark.locality)")
print("name: \(placemark.name)")
print("country: \(placemark.country)")
print("formatted address: \(placemark.addressDictionary)")
}
})
它在大多数情况下都非常有效。但是,我最近注意到一些失败的情况。以下是一些示例的输出:
搜索“米兰” - WORKS
locality: Optional("Milan")
name: Optional("Milan")
country: Optional("Italy")
formatted address: Optional([SubAdministrativeArea: Milan, State: Lombardy, CountryCode: IT, Country: Italy, Name: Milan, FormattedAddressLines: (
Milan,
Italy
), City: Milan])
这是正确的输出
搜索“Italy, TX” - 工作
德克萨斯州有一个小镇叫意大利。如果我输入“Italy, TX”,则输出为:
locality: Optional("Italy")
name: Optional("Italy")
country: Optional("United States")
formatted address: Optional([SubAdministrativeArea: Ellis, State: TX, CountryCode: US, Country: United States, Name: Italy, FormattedAddressLines: (
"Italy, TX",
"United States"
), City: Italy])
搜索“意大利” - 失败
当我只输入“意大利”时,我只会得到国家的地标:
locality: nil
name: Optional("Italy")
country: Optional("Italy")
formatted address: Optional([CountryCode: IT, Name: Italy, FormattedAddressLines: (
Italy
), Country: Italy])
搜索“新加坡,新加坡” - WORKS
这与“Italy, TX”的情况类似:
locality: Optional("Singapore")
name: Optional("Singapore")
country: Optional("Singapore")
formatted address: Optional([City: Singapore, CountryCode: SG, Name: Singapore, State: Singapore, FormattedAddressLines: (
Singapore,
Singapore
), Country: Singapore])
搜索“新加坡” - 失败
再次,似乎与“意大利”的情况相似。它只找到一个国家:
locality: nil
name: Optional("Singapore")
country: Optional("Singapore")
formatted address: Optional([CountryCode: SG, Name: Singapore, FormattedAddressLines: (
Singapore
), Country: Singapore])
初步猜测
在这个阶段,如果geocodeAddressString: 找到名称与搜索参数相同的国家/地区,我可能会停止搜索,所以我尝试将代码更改为:
let addrDict = [kABPersonAddressCityKey as NSString: searchBar.text!]
CLGeocoder().geocodeAddressDictionary(addrDict, completionHandler:{ (placemarks, error) -> Void in
print(placemarks)
})
我认为通过将搜索词限制为城市名称,我会得到正确的结果。不幸的是,我得到了完全相同的行为!
然后然后我意识到我不仅在城市名称等于国家名称的情况下遇到问题。
搜索“东京” - EPIC FAIL
locality: nil
name: Optional("Tokyo")
country: Optional("Japan")
formatted address: Optional([CountryCode: JP, Name: Tokyo, State: Tokyo, FormattedAddressLines: (
Tokyo,
Japan
), Country: Japan])
结论
CLGeocoder 不仅可以省略结果(例如在“意大利”的情况下),而且它还可以告诉我一个地方没有locality,而事实上它确实存在(我相信上次我检查地图东京仍然是一个城市!)。
有谁知道我可以如何解决这些问题?
天气应用程序以某种方式执行此操作 - 在那里搜索“新加坡”或“意大利”会得到正确的结果。如有任何帮助,我将不胜感激!
附:尽管我使用的是 Swift,但我将 Objective-C 添加为标签,因为我认为这个问题不是 Swift 特有的。
【问题讨论】:
-
只是检查一下,您是否使用任何解决方案解决了您的问题?
标签: ios objective-c swift swift2 clgeocoder