我正在尝试在识别长按手势时在iOS CoreData中保存标记的位置。每当我调用手势时,应用程序总是会崩溃。我还将那两个的coreData类型设置为Double。如何以最简单的方式安全地存储coreData中的坐标,因为我对iOS开发还不是很熟悉。
@IBAction func saveLocation(_ sender: Any) {
guard let longPress = sender as? UILongPressGestureRecognizer else
{ return }
if longPress.state == .ended {
let touchLocation = longPress.location(in: mapView)
let coordinate = mapView.convert(touchLocation, toCoordinateFrom: mapView)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newLocation = NSEntityDescription.insertNewObject(forEntityName: "GeoData", into: context)
newLocation.setValue(coordinate.latitude as Double, forKey: "myLatitude")
newLocation.setValue(coordinate.longitude as Double, forKey: "myLongitude")
do
{
try context.save()
}
catch
{
//ERROR
}
}
}
答案 0 :(得分:0)
我创建了一个长按手势并将位置存储到核心数据 -
创建长按手势并在核心数据中保存位置。
let longGesture = UILongPressGestureRecognizer(target: self, action:
#selector(longTap(_:)))
mapView.addGestureRecognizer(longGesture)
func longTap(_ sender: UIGestureRecognizer){
print("Long tap")
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
let touchLocation = sender.location(in: mapView)
let coordinate = mapView.convert(touchLocation,
toCoordinateFrom: mapView)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newLocation =
NSEntityDescription.insertNewObject(forEntityName: "GeoData", into:
context)
newLocation.setValue(coordinate.latitude as Double, forKey:
"myLatitude")
newLocation.setValue(coordinate.longitude as Double, forKey:
"myLongitude")
do
{
try context.save()
}
catch
{
//ERROR
print(error)
}
}
else if sender.state == .began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
}
}