经过对HitList和ToDo应用程序的详尽搜索和构建之后,我还没有接近实施Core Data和MKAnnotations的使用。我已经看到使用NSFetchedResults,NSUserDefaults或其他废话的各种建议。我想知道如何实现保存引脚位置,然后从CoreData中检索它。以下是我徒劳的尝试。使用核心数据在Swift 3中保存和检索MKAnnotations
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
var locationManager: CLLocationManager!
var storedLocations: [StoredLocations]! = []
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var markSpot: UIBarButtonItem!
@IBOutlet weak var segmentedControl: UISegmentedControl!
// Part of the Fail
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isToolbarHidden = false
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
let trackingButton = MKUserTrackingBarButtonItem(mapView: mapView)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolbarItems = [trackingButton, flexibleSpace, markSpot]
mapView.delegate = self
// More Fail
mapView.addAnnotation(getData() as! MKAnnotation)
}
// Miserable Fail.. Again
func getData() {
do {
storedLocations = try context.fetch(StoredLocations.fetchRequest())
}
catch {
print("Fetching Failed")
}
}
@IBAction func markSpotPressed(_ sender: Any) {
let annotation = MKPointAnnotation()
let userLatitude = mapView.userLocation.coordinate.latitude
let userLongitude = mapView.userLocation.coordinate.longitude
annotation.coordinate = CLLocationCoordinate2D(latitude: userLatitude, longitude: userLongitude)
annotation.title = "Dropped Pin"
mapView.addAnnotation(annotation)
// Another Part of the Fail
let newPin = StoredLocations(context: context)
newPin.latitude = userLatitude
newPin.longitude = userLongitude
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
阵列代码不从工作看太远;你需要遍历返回到'storedLocations'的对象,并使用纬度和经度来重新创建注释对象。 – Paulw11
@ Paulw11那么知道我整整一天的半安慰并不是完全浪费阅读和构建演示。如果我不太远,我会选择睡觉,或者有人会过来帮助它。我的大脑被炸。 – Chilly