經過對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