1
我有一個CLLocationManager小問題。當我點擊IBAction「addPlace」時,應用程序崩潰。我沒有看到問題,我不明白爲什麼應用程序崩潰。CLLocationManager - 致命錯誤:意外地發現零,而解包一個可選值
非常感謝您的回覆。
class Map: UIViewController, CLLocationManagerDelegate {
// Outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var BTNAdd: UIButton!
// Variables
var positionManager = CLLocationManager()
var geoCoder : CLGeocoder!
var placemark : CLPlacemark!
var name: String = ""
var address: String = ""
var longitude: String = ""
var latitude: String = ""
// Actions
@IBAction func myPosition(sender: AnyObject) {
positionManager.delegate = self
positionManager.desiredAccuracy = kCLLocationAccuracyBest
positionManager.requestWhenInUseAuthorization()
positionManager.startUpdatingLocation()
mapView.showsUserLocation = true
}
@IBAction func addPlace(sender: AnyObject) {
///////////////////////////////////////
// BUG HERE
///////////////////////////////////////
let locality = String(self.placemark.locality)
let postalCode = String(self.placemark.postalCode)
let administrativeArea = String(self.placemark.administrativeArea)
let country = String(self.placemark.country)
print(locality + postalCode + administrativeArea + country)
///////////////////////////////////////
///////////////////////////////////////
}
// Functions
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if let pm = placemarks?.first {
self.displayLocationInfo(pm)
}
})
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
positionManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
}
}
}
謝謝爲了你的迴應,但我在地標上有一個錯誤:在關閉中引用屬性'地標'需要'自我'。明確捕獲語義。如果我添加self.placemark,並刪除其他自己,則沒有錯誤,但只有「地標爲零」顯示。 –
不客氣。這就是目標:處理錯誤以阻止您的應用崩潰。 :)如果您看到「地標爲零」的行,這是因爲,*地標是無*。它回答了你的問題,即「我沒有看到問題,我不明白爲什麼應用程序崩潰。」現在你看到並理解了:一個明確解開的可選項,它是零。 – Moritz