当长按手势被识别时,我试图在 iOS CoreData 中保存标记位置。每当我调用手势时,应用程序总是崩溃。我还将这两个的 coreData 类型设置为 Double。由于我对 iOS 开发还不是很熟悉,如何以尽可能简单的方式安全地将坐标存储在 coreData 中。
@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
}
}
}
最佳答案
我创建了一个长按手势并将位置存储到这样的核心数据中--
创建长按手势并将位置保存在核心数据中。
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
}
}
关于ios - 如何在 CoreData 中保存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46271312/