在我的项目中,当用户按下屏幕时,地图视图上会出现一个图钉,并将该图钉保存到UserDefaults。在底部功能中,当用户选择mapView上已经存在的图钉时,该图钉将被删除。但是,我不确定如何确保通过UserDefaults将该引脚保持删除状态……对于最后一行代码,我将使用什么?
@IBAction func addPin(_ sender: UILongPressGestureRecognizer) {
guard sender.state == .ended else { return }
let location = sender.location(in: self.mapView)
let locCoord = self.mapView.convert(location, toCoordinateFrom: self.mapView)
let annotation = MKPointAnnotation()
annotation.coordinate = locCoord
annotation.title = titleTextField.text
self.mapView.addAnnotation(annotation)
//Create a dictionary from the annotation
let newAnnotationDict = [
"lat": locCoord.latitude,
"lng": locCoord.longitude,
"title": annotation.title
] as [String : Any]
//Pull the stored annotations data (if local)
var annotationsArray: [[String:Any]]!
var annotationsData = UserDefaults.standard.data(forKey: "StoredAnnotations")
//If the data is nil, then set the new annotation as the only element in the array
if annotationsData == nil {
annotationsArray = [newAnnotationDict]
} else {
//If it isn't nil, then convert the data into an array of dicts
do {
//Convert this data into an array of dicts
annotationsArray = try JSONSerialization.jsonObject(with: annotationsData!, options: []) as! [[String:Any]]
annotationsArray.append(newAnnotationDict)
} catch {
print(error.localizedDescription)
}
}
do {
//Use JSONSerialization to convert the annotationsArray into Data
let jsonData = try JSONSerialization.data(withJSONObject: annotationsArray, options: .prettyPrinted)
//Store this data in UserDefaults
UserDefaults.standard.set(jsonData, forKey: "StoredAnnotations")
} catch {
print(error.localizedDescription)
}
print("This will become the annotation title: \(titleTextField.text).")
print(annotation.coordinate.latitude, annotation.coordinate.longitude)
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
var selectedAnnotation = view.annotation
print("Selected Annotation: \((selectedAnnotation?.coordinate.latitude, selectedAnnotation?.coordinate.longitude))")
self.mapView.removeAnnotation(selectedAnnotation!)
// What do I use for the following line?
UserDefaults.standard.set(, forKey: "StoredAnnotations")
}
答案 0 :(得分:0)
最快的解决方案是:
从mapview main.c
通过执行以下操作,将mapView.annotations上的左侧转换为newAnnotationDict数组:
self.mapView.removeAnnotation(selectedAnnotation!)
然后将其序列化为数据,并像在代码中所做的那样覆盖UserDefaults值(而不是附加)。