swift - 引脚注释被复制
问题描述
我在我的项目中实现了核心数据代码并且引脚显示正确,但是,当我添加注释并使用 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
解决方案
推荐阅读
- reactjs - ESLint 为 reactjs 数据组件抛出 no-unused-vars
- templates - 使用 Blaze Meteor.js 动态加载模板(部分)
- visual-studio - 在预览模式 SSRS 下执行时调试查询
- c# - 在 C# 中使用 OData 服务不起作用
- woocommerce - 最后如何验证我的自定义 WooCommerce 结帐字段?
- c - 某些输入的整数到二进制转换程序失败
- amazon-web-services - AWS SAM Deploy,如何找到 API Gateway 的 URL?
- php - 复制而不是更新
- javascript - Grunt clean 删除目录根目录下的所有文件夹
- python - 使用无查找最小元素及其在列表中的位置