I'm trying to save a marked location in iOS CoreData when a long press gesture get recognized. Whenever I invoke the gesture, the app always crashes. I've also set the coreData type of those two to Double. How does one safely store coordinates in coreData in simplest way as possible as I'm still not very familiar with iOS development.
@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
}
}
}
I create a long tap gesture and storing location to core data like this--
Create a long tap gesture and Save location in core data.
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.