首页 > 解决方案 > 引脚注释被复制

问题描述

我在我的项目中实现了核心数据代码并且引脚显示正确,但是,当我添加注释并使用 save() 函数保存时,我创建的注释在关闭应用程序并再次运行后复制。

如果您运行该应用程序,则有一个打印语句用于显示引脚数。这是我的代码

class TravelLocationsMapViewController: UIViewController, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

var latitude: Double?
var logitude: Double?

var latitudeZoom: Double?
var logitudeZoom: Double?

var pins:[NSManagedObject] = []

var appDelegate: AppDelegate!
var sharedContext: NSManagedObjectContext!

override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self

    appDelegate = UIApplication.shared.delegate as! AppDelegate
            
    sharedContext = appDelegate.persistentContainer.viewContext
    
    fetchUserDefaultsDetailsForMap()
    
    let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(createNewAnnotation))
    uilpgr.minimumPressDuration = 0.25
    mapView.addGestureRecognizer(uilpgr)
    
}

override func viewWillAppear(_ animated: Bool) {
    
    print("--------------viewWillAppear----------------")
    super.viewWillAppear(animated)
    navigationController?.setNavigationBarHidden(true, animated: animated)
    
    viewAllPins()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.setNavigationBarHidden(false, animated: animated)
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
}


fileprivate func fetchUserDefaultsDetailsForMap() {
    let lat = UserDefaults.standard.double(forKey: "userLatitude")
    let long = UserDefaults.standard.double(forKey: "userLogitude")
    let latZoom = UserDefaults.standard.double(forKey: "userLatitudeDelta")
    let longZoom = UserDefaults.standard.double(forKey: "userLongitudeDelta")
    let location = CLLocationCoordinate2D(latitude: lat, longitude: long)
    
    latitudeZoom = latZoom
    logitudeZoom = longZoom
    
    mapView.setRegion(MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: latitudeZoom!, longitudeDelta: logitudeZoom!)), animated: false)
}
    
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {

    latitude = mapView.centerCoordinate.latitude
    logitude = mapView.centerCoordinate.longitude
    
    latitudeZoom = mapView.region.span.latitudeDelta
    logitudeZoom = mapView.region.span.longitudeDelta
    
    UserDefaults.standard.set(latitude, forKey: "userLatitude")
    UserDefaults.standard.set(logitude, forKey: "userLogitude")
    UserDefaults.standard.set(latitudeZoom, forKey: "userLatitudeDelta")
    UserDefaults.standard.set(logitudeZoom, forKey: "userLongitudeDelta")
}

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    let reuseId = "pin"

    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView

    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView!.canShowCallout = true
        pinView!.pinTintColor = .red
        pinView!.rightCalloutAccessoryView = UIButton(type: .infoDark)
    }
    else {
        pinView!.annotation = annotation
    }

    return pinView
}

@objc func createNewAnnotation(_ sender: UIGestureRecognizer) {
    
    let touchPoint = sender.location(in: self.mapView)
    let coordinates = mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
    let heldPoint = MKPointAnnotation()
    heldPoint.coordinate = coordinates

    if (sender.state == .began) {
        heldPoint.title = "Set Point"
        heldPoint.subtitle = String(format: "%.4f", coordinates.latitude) + "," + String(format: "%.4f", coordinates.longitude)
        mapView.addAnnotation(heldPoint)
    }
    
    save(latitude: coordinates.latitude, longitude: coordinates.longitude)
    
    sender.state = .cancelled
}

func viewAllPins() {
    
    print("--------------viewAllPins---------------")
    var annotations = [MKPointAnnotation]()
    
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Pin")
      
    do {
        pins = try sharedContext.fetch(fetchRequest)
        print("number of annotation that added: \(pins.count)")
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
    
    for pin in pins {
        let lat = CLLocationDegrees(pin.value(forKey: "latitude") as! Double)
        let long = CLLocationDegrees(pin.value(forKey: "longitude") as! Double)
        
        let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
        
        let annotation = MKPointAnnotation()
        annotation.coordinate = coordinate
        annotation.title = "\(lat) -- \(long)"
        
        print(pin)
        annotations.append(annotation)
        
        self.mapView.addAnnotations(annotations)
        
    }
    
}


func save(latitude: Double, longitude: Double) {
  
    let entity = NSEntityDescription.entity(forEntityName: "Pin", in: sharedContext)!
  
    let pin = NSManagedObject(entity: entity, insertInto: sharedContext)
  
    pin.setValue(latitude, forKeyPath: "latitude")
    pin.setValue(longitude, forKeyPath: "longitude")
  
  do {
    try sharedContext.save()
  } catch let error as NSError {
    print("Could not save. \(error), \(error.userInfo)")
  }
}

}

如果有人想测试它,这是项目 GitHub

标签: swiftcore-datamkmapview

解决方案


推荐阅读