使用CoreData中保存的坐标将注释固定到mapView

时间:2016-07-06 11:59:57

标签: ios arrays swift core-data swift2

我现在已经在互联网上搜索过了,我几乎尝试了所有东西。我目前的项目是:

我从用户位置读取当前坐标并在CoreData中保存纬度和经度以及此地点的名称(用户可以给出名称)

 // MARK: - AddPlace Button Events

@IBAction func onAddButton(sender: AnyObject) {

        //searching the current location
        let locCoord = CLLocationCoordinate2DMake(self.locationManager.location!.coordinate.latitude, self.locationManager.location!.coordinate.longitude)

        // 1. pass the data from the current location to lat and lng
        let lat = locCoord.latitude
        let lng = locCoord.longitude

        let ed = NSEntityDescription.entityForName("Store", inManagedObjectContext: moContext)
        let store = Store(entity: ed!, insertIntoManagedObjectContext: moContext)

        // 2. give the passed data to the array from CoreData
        store.storeName = noteTextField.text
        store.storeLng = lng
        store.storeLat = lat



        do  {
            // 3. save the informations in CoreData
            try moContext.save()
            noteTextField.text  = ""
            lat
            lng

            // 4. testing if the coordinates are saved - it works!
            print(store.storeLat)
            print(store.storeLng)

现在我的问题是在另一个带有mapView的ViewController中的保存位置上显示一个图钉。我试过了:

更新

storeLat - >存储为Double

storeLng - >存储为Double

storeName - >存储为String

//MARK: - Second ViewController with a mapView



    override func viewDidLoad() {
      super.viewDidLoad()

    // Initialize Fetch Request
    let fetchRequest = NSFetchRequest()

    // Create Entity Description
    let entityDescription = NSEntityDescription.entityForName("Store", inManagedObjectContext: self.moContext)

    // Configure Fetch Request
    fetchRequest.entity = entityDescription
    do {
        stores = try moContext.executeFetchRequest(fetchRequest) as! [Store]
        if stores.count > 0
        {

            print("Test")
            // add the annotation
            let annotation = MKPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: store!.storeLat as! Double, longitude: store!.storeLng as! Double)
            annotation.title = store?.storeName
            self.mapView.addAnnotation(annotation)

        } else
        {
            let alert = SCLAlertView()
            alert.showError("Keine Places", subTitle: "Du hast noch keine Places gespeichert.")
        }
    } catch {
        fatalError("Failed to fetch Places: \(error)")
    }

现在进入if - Statement。但是当我想要放置注释时,我会失败。致命错误:在展开Optional值时意外发现nil。我想我已经忘了要申报的东西了。有人可以帮忙吗?谢谢你!

更新2

我发现这很棒site。但我还有一些问题。

0 个答案:

没有答案