Как обновить UserDefaults после удаления MKAnnotation? - PullRequest
0 голосов
/ 05 октября 2019

В моем проекте, когда пользователь нажимает на экран, пин-код появляется в mapView, и пин-код сохраняется в 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")

}

1 Ответ

0 голосов
/ 05 октября 2019

самым быстрым решением было бы: после удаления аннотации из 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, как вы уже сделали в своем коде.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...