swift - CLLocationManager、核心数据和数组

标签 swift core-data mapkit core-location cllocationmanager

我已经获得了这个功能,并且非常接近让它发挥作用!我想我遇到了转换问题。我可以将坐标放入具有 3 个属性纬度( double )、经度( double )和时间(日期)的实体中。这行得通,我可以将内容打印到屏幕上,看起来不错。但是当我尝试提取并用作 map 上的坐标时,它不起作用。我认为这是因为它们没有被识别为真实坐标。有什么想法吗?

   func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        //ARRAY for lat/long data
        var latArr:[Double] = []
        var longArr:[Double] = []
        var timeArr:[Date] = []

        let location = locations[0]
        let annotation = MKPointAnnotation()
        let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
        let myLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        //annotation.coordinate = myLocation
        //annotation.title = "\(location.timestamp)"
        //self.mapView.addAnnotation(annotation)
        let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
        self.mapView.setRegion(region, animated: true)
        self.mapView.showsUserLocation = false //SET THIS
        latitude.text = "latitude: " + "\(location.coordinate.latitude)"
        longitude.text = "longitude: " + "\(location.coordinate.longitude)"
        altitude.text = "altitude: " + "\(location.altitude)"
        speed.text = "speed: " + "\(location.speed)"
        timestamp.text = "timestamp: " + "\(location.timestamp)"

        //START -- Core Data
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
        request.returnsObjectsAsFaults = false

        let data = NSEntityDescription.insertNewObject(forEntityName: "Data", into: context)
        //let data = NSNumber(double: self.location?.coordinate.latitude)

        let dlat = Double("\(location.coordinate.latitude)")
        let dlong = Double("\(location.coordinate.longitude)")

        data.setValue(dlat, forKey: "lat")
        data.setValue(dlong, forKey: "long")
        data.setValue(location.timestamp, forKey: "time")
        //END -- Core Data

        do
        {
            try context.save()
            //print("Saved")
        }
        catch
        {

        }

        do
        {
            var lat: Double = 0
            var long: Double = 0
            let t = NSDate()
            let results = try context.fetch(request)

            if results.count > 0
            {
                for result in results as! [NSManagedObject]
                {
                    if let datalat = result.value(forKey: "lat") as? Double
                    {
                        //latArr.append(datalat)
                        let lat = datalat
                        print(lat)
                    }
                    if let datalong = result.value(forKey: "long") as? Double
                    {
                        //longArr.append(datalong)
                        let long = datalong
                        print(long)
                    }
                    if let time = result.value(forKey: "time") as? Date
                    {
                        //timeArr.append(time)
                        let t = time
                        print(t)
                    }
                    let mLocation = CLLocationCoordinate2DMake(lat, long)
                    annotation.coordinate = mLocation
                    annotation.title = "\(t)"
                    self.mapView.addAnnotation(annotation)
                }
            }
        }
        catch
        {

        }

最佳答案

我将您的代码与我在类似场景中使用的函数进行了比较,并合并了所有差异(并为简洁起见进行了一些编辑,您可以接受或离开)。相关部分如下:

    let request = NSFetchRequest<Data>(entityName: "Data")
let annotations: [MKAnnotation] = []

annotation.title = “\(t)”

for result in results  
{
    if data.lat != nil && data.lon != nil
    {
        annotation.coordinate = CLLocationCoordinate2D(latitude: data.lat.doubleValue, longitude: data.lon.doubleValue)
        annotations.append(annotation)
    }
    self.mapView.addAnnotations(annotations)
    self.mapView.showAnnotations(annotations, animated: false)
}

我的代码有效,但它是 Swift 3.0,因此如果您使用的是 2.2. 或 2.3,则一些差异可能是由于较早版本的更改所致。我知道我需要将它从 NSNumber(从 CoreData)推到 Double,但我认为如果这是问题所在,你会得到一个编译错误 - 不确定为什么不是。正如我在评论中提到的,如果航路点只是在可见 map 区域之外,显示注释将有所帮助。

除此之外,您的代码在我看来还不错 - 让我知道它是否仍然有效。

关于swift - CLLocationManager、核心数据和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41385737/

相关文章:

ios - 如何在 Swift 中仅在 View Controller 的一部分上实现滑入/滑出菜单?

objective-c - 保存一个自定义对象数组,每个对象包含一个自定义对象数组,最好的方法是什么?

swift - 当我将核心数据添加到 TableView 时,我的应用程序崩溃了

ios - swift - MapKit 中的自定义注释偏移

ios - 尝试获取 iOS MKCoordinateSpan 的跨度大小(以米为单位)

arrays - Swift 中 MemoryLayout.size 中数组的大小

ios - 使用基本身份验证进行 Rest API 调用

ios - 在 Swift 中为 mapView 上的每个注释显示不同的图像

cocoa - 自动生成多对键谓词行模板?

iOS - 使用 3G/蜂窝网络时清空 map 图 block /将 map 切换到离线模式