我已經有了這個功能,並且非常接近它的工作原理!我想我有一個轉換問題。我可以將座標轉換爲具有3個屬性lat(Double),long(Double)和time(Date)的實體。這有效,我可以將內容打印到屏幕上,而且看起來不錯。但是當我嘗試提取並在地圖上使用座標時,它不起作用。我認爲這是因爲他們沒有被認爲是真正的座標。有任何想法嗎?CLLocationManager,核心數據和陣列
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(註釋,動畫:false) –