Search code examples
swiftswiftuirealm

Swift Saving Structured Data to realm database


I am Developing my app using SwiftUI and for my database i have chosen to use Realm database.

My App record Driver Trip stats and the stats looks like this object:

    class TripModel: Object, ObjectKeyIdentifiable {
    
    @Persisted(primaryKey: true) var id: ObjectId
    
    @Persisted var tripMaxSpeed: String = "0"
    @Persisted var tripAvgSpeed: String = "0"
    @Persisted var tripDistance: String = "0"
    @Persisted var tripDuration: Int = 0
    @Persisted var tripDate: Date = Date()
    @Persisted var tripFavorite: Bool = false
    
    var coordinates = List<TripRoute>() // We have a list of CLCoord2D we want to cast it to TripRoute
    
}

class TripRoute: Object {
    @Persisted var latitude = 0.0
    @Persisted var longitude = 0.0

    /// Computed properties are ignored in Realm
    var coordinate: CLLocationCoordinate2D {
        return CLLocationCoordinate2D(
            latitude: latitude,
            longitude: longitude)
    }
}

When the user open the app they have a button to start the trip and the trip stats starts updating in my viewModel, i also have a boolean variable that get triggered when my user press the the button to start trip like the code down below

class LocationManager: NSObject, ObservableObject {

@Published var startTrip = false {
        didSet {
            //When trip start == true then rest all value and start from zero
           

            
            if startTrip == true {
                tripTimer = 0
                allSpeeds.removeAll()
                tripMaxSpeed = 0
                tripDistance = 0
                allLocations.removeAll()
            }
            
            //When Trip ends write the trip to Realm Database for Saving
            if startTrip == false {
                addTrip()
            }
            
        }
    }

}

as explained in the above code whenever the start trip value changes to false a new trip is added to the database with the addTrip() function and all works fine and well except the array coordinate which fails to be added, here is the addTrip() function:

 func addTrip() {
    if let localRealm = localRealm {
        do {
            print("DEBUG: Trying to add trip")
            try localRealm.write({
                
                let trip = TripModel()
                
                for location in allLocations {
                    let tripRoute = TripRoute()
                    tripRoute.latitude = location.longitude
                    tripRoute.longitude = location.longitude
                    trip.coordinates.append(tripRoute)
                }
                
                trip.tripMaxSpeed = tripMaxSpeed.converted.roundedString
                trip.tripAvgSpeed = allSpeeds.average()
                trip.tripDistance = tripDistance.convertDistance.roundedString1
                trip.tripDuration = tripTimer
                trip.tripDate = Date()
                
                localRealm.add(trip)
                getTrips()
            })
        } catch {
            print("ERROR: error adding trip to realm \(error.localizedDescription)")
        }
    }
}

All tripInformation except the tripRoute gets added successfully and all get fetched with no problem, i am not sure why the array inside my object is empty and doesn't save.

What i want to accomplish with the list of coordinate is to show the user track line in their history map of the trip they took.

enter image description here


Solution

  • You need to persist the container too.

    @Persisted var coordinates = List<TripRoute>()
    

    The TripRoute objects are probably stored in the db somewhere but there is nothing tying them to your TripModel object.