我已将this code用于我的应用。在+/- 50
跟踪我的路线之后,它的工作效果很好但有时会崩溃。我知道它与选项“?”有关,但我无法让它起作用。
我收到以下消息:
致命错误:在打开可选
时意外发现nil
代码中断的部分:
if let locationName = placeMark.addressDictionary?["Name"] as? NSString
{
print(locationName)
self.locationName = locationName as String
}
完整的locationManager代码:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations as [CLLocation] {
let howRecent = location.timestamp.timeIntervalSinceNow
//start motion tracker
motionTracker()
//location name tracker
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
let latitude: CLLocationDegrees = locValue.latitude
let longitude: CLLocationDegrees = locValue.longitude
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location)
{
(placemarks, error) -> Void in
let placeArray = placemarks as [CLPlacemark]!
// Place details
var placeMark: CLPlacemark!
placeMark = placeArray?[0]
// Address dictionary
print(placeMark.addressDictionary)
// Location name
if let locationName = placeMark.addressDictionary?["Name"] as? NSString
{
print(locationName)
self.locationName = locationName as String
}
// Street address
if let street = placeMark.addressDictionary?["Thoroughfare"] as? NSString
{
//print(street)
self.locationStreet = street as String
}
// City
if let city = placeMark.addressDictionary?["City"] as? NSString
{
self.locationCity = city as String
//print(city)
}
// Zip code
if let zip = placeMark.addressDictionary?["ZIP"] as? NSString
{
//print(zip)
}
// Country
if let country = placeMark.addressDictionary?["Country"] as? NSString
{
//print(country)
}
}
答案 0 :(得分:2)
我怀疑您遇到的情况是Google没有针对您所在位置的反向地理编码结果并返回一个空数组。
而不是:
let placeArray = placemarks as [CLPlacemark]!
var placemark: CLPlacemark!
placemark = placeArray?[0]
...假设将有一个数组并且它将始终包含至少一个元素,请使用:
if let placemark = placemarks?.first {
// Rest of your code
}