---
title: "[EP] Improving the iCloud sync"
slug: ep-improving-the-icloud-sync
section: tech
date: 2015-06-24T14:27:00.000Z
canonical: https://roland.leth.ro/blog/tech/ep-improving-the-icloud-sync
---

When I wrote about [iCloud sync](/tech/blog/ep-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:

```swift
let event = EPEvent(
  id: Events.last?.id ?? 0 + 1,
  ...
)

EPEvent.data.append(event)

init(...) {
  modificationTime = Date.timeIntervalSinceReferenceDate()
}

modifyEventInAnyWay() {
  modificationTime = Date.timeIntervalSinceReferenceDate()
}
```

Then the sync.

```swift
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)
  }
```