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)")
}
})
在大多数情况下它都工作得很好。但是,我最近注意到一些失败的情况。以下是一些示例的输出:
搜索“米兰” - 工作正常
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' - 成功
Texas州有一个名叫Italy的城镇。如果我输入 '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])
搜索'Singapore, Singapore' - 已找到
这与 '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)
})
我本以为将搜索词限制在城市名称上可以得到正确的结果。不幸的是,我却遇到了完全相同的问题!
后来我才意识到,我的问题不仅出现在城市名称等于国家名称的情况下。
搜索“东京” - 失败了
locality: nil
name: Optional("Tokyo")
country: Optional("Japan")
formatted address: Optional([CountryCode: JP, Name: Tokyo, State: Tokyo, FormattedAddressLines: (
Tokyo,
Japan
), Country: Japan])
结论
CLGeocoder
不仅可以省略结果(例如在“意大利”这种情况下),而且还可以告诉我一个地方没有 locality
,即使实际上它有(我相信上次我查看东京地图时它仍然是一座城市!)。
有人知道如何解决这些问题吗?
天气应用程序以某种方式执行此操作 - 在那里搜索“新加坡”或“意大利”将提供正确的结果。 我将感激任何帮助!
P.S. 尽管我正在使用Swift,但我将Objective-C添加为标签,因为我认为这个问题不限于Swift。