ios - 如何在 CoreData 中保存位置

标签 ios swift core-data android-mapview

当长按手势被识别时,我试图在 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/

相关文章:

iphone - 如何确定 UITextField 中删除的位置

ios - 由于解包导致网络调用失败

objective-c - 核心数据查询中的 fetchLimit 和 fetchOffset 可能存在问题

javascript - 按钮可见性属性在 Kony 的 iOS 上不起作用

ios - 从 iPhone SDK 中的视频 url 创建缩略图

ios - 在我的项目中包括一个 Playground

swift - 用 SpriteKit 在矩形上画一个洞?

ios - Swift:使 UIGestureRecognizer 只影响一个 UICollectionViewCell 而不是所有

core-data - iOS NSDate 核心数据比较获取请求不起作用

core-data - Xcode4 核心数据关系