swift - 删除 MKAnnotation 后如何更新 UserDefaults?

标签 swift mapkit mkmapview userdefaults mapkitannotation

在我的项目中,当用户按下屏幕时, map View 上会出现一个图钉,并且该图钉会保存到 UserDefaults 中。在底部函数中,当用户选择 map View 上已有的图钉时,它将被删除。但是,我不确定如何确保该 pin 通过 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")

}

最佳答案

最快的解决方案是: 从mapview删除注释后 self.mapView.removeAnnotation(selectedAnnotation!)

通过执行以下操作将剩余的 mapView.annotations 转换为 newAnnotationDict 数组:

let newArray = self.mapView.annotations.map({ ["title": $0.title, "lat": $0.coordinate.latitude, "lng": $0.coordinate.longitude] as [String: Any]})

然后将其序列化为数据并覆盖(而不是附加)UserDefaults 值,就像您在代码中所做的那样。

关于swift - 删除 MKAnnotation 后如何更新 UserDefaults?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249889/

相关文章:

ios - MapView随机标注图像

ios - map View :regionDidChangeAnimated: never called

ios - MKMapView隐藏 basemap 图层

ios - Swift - 优化使用非常长的数组

swift - 循环遍历源代码中的多个实例?

ios - 从解析加载对象并显示在 map 上

iphone - 如何将 uibutton 添加到自定义注释 View

json - Swift - 解析数据错误 - Swift.DecodingError.dataCorrupted

ios - 如何根据键盘大小正确实现 View 的缩小和扩展?

ios - 删除 MKAnnotation Swift4 后 MapView 不更新 View