Having issues when reading using coreData as the data type has a CLPlacemark

70 views Asked by At

I've have an entity called Places and an attribute(placeMark) which is and of Transformable. I'm having an issue when I close the app and re-launch it, it queries CoreData and the records are there however the timestamp of each of these places is exactly the same.

**Code to write to CoreData **

private func store(_ location: CLLocation) {
    if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
      let newData = Places(context: context)
      CLGeocoder().reverseGeocodeLocation(location, completionHandler:
        { (placeMarks, error) in
          if (error != nil) {
            print("reverse geodcode fail: \(error!.localizedDescription)")
          }
          let placeMark = placeMarks! as [CLPlacemark]
          if placeMark.count > 0 {
            // add to the database
            newData.placeMark = placeMark[0]
            print(newData.placeMark?.location?.timestamp as Any)
            self.places.append(newData)
            self.lastPlaceForAllLocations = newData
          }
          //Save the context
          (UIApplication.shared.delegate as? AppDelegate)?.saveContext()
          
          // test if this works if we clear all placemarks
          //self.getLocationFromDatabase()
        })
    }
  }

Once I get a location(ClLocation) I am able to store, erase my context and read back time(different timestamps). I use the code below to read the database.

**Core to read from CoreData **

private func getLocationFromDatabase() {
    places.removeAll()
    if let context = (UIApplication.shared.delegate as? AppDelegate)?
      .persistentContainer.viewContext {
      let request: NSFetchRequest<Places> = Places.fetchRequest()
      /*let sort = NSSortDescriptor(key: "placeMark.location.timestamp", ascending: false)
      request.sortDescriptors = [sort]*/
      if let placesCoreData = try?
        context.fetch(request) {
        if let placesHere = placesCoreData as? [Places] {
          print(placesHere)
          for item in placesHere {
            print(item.placeMark?.location?.timestamp)
            self.places.append(item)
          }
          lastPlaceForAllLocations = places.last
          // TODO
          //tableView.reloadData()
        }
      }
    }
    lastPlaceForAllLocations = places.first
  }

I try storing a Placemark and then I clear my buffer and read and its ok(I am able to see two places with different timestamps), however once, launch the app again, I am able to read to read both placemarks's but they have the same timestamp.

Any help would be appreciated!

0

There are 0 answers