ヒットリストと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