【发布时间】:2016-12-29 19:02:13
【问题描述】:
我已经有了这个功能,而且离让它工作很近了!我想我遇到了转换问题。我可以将坐标转换为具有 3 个属性 lat(Double)、long(Double)和 time(Date)的实体。那行得通,我可以将内容打印到屏幕上,而且看起来不错。但是当我尝试提取并用作地图上的坐标时,它不起作用。我认为这是因为它们没有被识别为真正的坐标。有什么想法吗?
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
{
}
【问题讨论】:
-
“它不起作用”具体是什么方式?
-
永远不会有空的 catch{} 语句。至少在其中放一个日志语句。错误可能会出现,但您现在永远不会知道它们,不是吗?
-
您确定显示的是地图的正确区域吗?为了安全起见,您可以添加 mapView.showAnnotation(annotation, animated: false)
标签: swift core-data mapkit core-location cllocationmanager