When I wrote about iCloud sync, I said the sync logic is the shittiest ever, so this is the first attempt at improving it.
Firstly, the migrateOldData
got an update:
let event = EPEvent(
id: Events.last?.id ?? 0 + 1,
...
)
EPEvent.data.append(event)
init(...) {
modificationTime = Date.timeIntervalSinceReferenceDate()
}
modifyEventInAnyWay() {
modificationTime = Date.timeIntervalSinceReferenceDate()
}
Then the sync.
for iCloudEvent in document.data {
var addEvent = true
for localEvent in Events where localEvent.id == iCloudEvent.id {
if localEvent.lastModification < iCloudEvent.lastModification {
// Update local events.
}
// We use an inner if block instead of adding it in the where statement,
// because if iCloud modification is older than local,
// we don't want to add a new event, just not update the local one.
addEvent = false
}
// Add new event.
if addEvent {
Events.append(iCloudEvent)
}