iCloud Sync: CloudKit & NSUbiquitousKeyValueStore Integration

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
iCloud Sync: CloudKit & NSUbiquitousKeyValueStore Integration
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1159
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

Note: When a user changes an iPhone, the app's data should appear on the new device automatically. Otherwise, you lose the customer. We integrate iCloud synchronization via three mechanisms: NSUbiquitousKeyValueStore, CloudKit, and iCloud Documents (UIDocument). Each solves its own task, but for complex synchronization with minimal latency, CloudKit is the best choice. Syncing data via iCloud is not just file transfer—it's a complex process with deltas, conflicts, and storage limitations. Without proper architecture, the user loses progress, settings, or notes when switching devices.

One of our projects is a note-taking app with multi-user editing. The first version uploaded all notes in full at every launch. Traffic exceeded 10 MB per user per day. Switching to delta synchronization with serverChangeToken reduced transferred data to 1 MB—a 90% reduction. Users stopped complaining about slow loading, and the number of requests to CloudKit decreased tenfold.

When to use NSUbiquitousKeyValueStore, CloudKit, or iCloud Documents?

Criterion NSUbiquitousKeyValueStore CloudKit iCloud Documents
Maximum volume 1 MB, 1024 keys 10 MB/user (free), additional 1 GB for $0.99/month Limited by iCloud free space
Data type Settings, simple configurations Arbitrary records (notes, progress, lists) Files, images, documents
Synchronization Automatic, no code Requires subscriptions and delta updates Automatic via UIDocument
Conflict support Last write wins Manual merge for custom zones Versioning (UIDocument)

Apple provides 10 MB free CloudKit storage per user, additional 1 GB costs $0.99 per month. Traffic savings from delta sync can reduce query costs by 5 times.

NSUbiquitousKeyValueStore

The simplest option—for small configuration data. Limit: 1 MB total storage, 1024 keys, up to 256 KB per key. Synced automatically, no sync code required.

let store = NSUbiquitousKeyValueStore.default

// Write
store.set(userId, forKey: "lastUserId")
store.set(["theme": "dark", "fontSize": 16], forKey: "userSettings")
store.synchronize() // requests immediate sync, not guaranteed

// Read
let theme = store.string(forKey: "userSettings.theme") ?? "light"

// Subscribe to changes from other devices
NotificationCenter.default.addObserver(
    self,
    selector: #selector(iCloudDidChange),
    name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
    object: NSUbiquitousKeyValueStore.default
)

@objc func iCloudDidChange(_ notification: Notification) {
    guard let keys = notification.userInfo?[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String]
    else { return }
    // Update local state for changed keys
    keys.forEach { updateLocalState(forKey: $0) }
}

Ideal for settings. For game progress, notes, files—CloudKit.

Why choose CloudKit for complex synchronization?

CloudKit is a full-fledged database in iCloud. Three storage types:

Database type Visibility Quota consumption Example usage
Private Database Only the user User's Personal notes, settings
Public Database All users Developer's App content, ratings
Shared Database Selected users User's Collaborative lists, editing
import CloudKit

class CloudKitManager {
    let container = CKContainer(identifier: "iCloud.com.company.appname")
    var privateDB: CKDatabase { container.privateCloudDatabase }

    // Save a note
    func saveNote(_ note: Note) async throws {
        let record = CKRecord(recordType: "Note",
                              recordID: CKRecord.ID(recordName: note.id))
        record["title"] = note.title as CKRecordValue
        record["content"] = note.content as CKRecordValue
        record["modifiedAt"] = Date() as CKRecordValue
        record["isPinned"] = note.isPinned as CKRecordValue

        let savedRecord = try await privateDB.save(record)
        print("Saved: \(savedRecord.recordID.recordName)")
    }

    // Fetch all notes
    func fetchAllNotes() async throws -> [Note] {
        let predicate = NSPredicate(value: true)
        let query = CKQuery(recordType: "Note", predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: "modifiedAt", ascending: false)]

        let (results, _) = try await privateDB.records(matching: query)
        return results.compactMap { (_, result) in
            guard let record = try? result.get() else { return nil }
            return Note(
                id: record.recordID.recordName,
                title: record["title"] as? String ?? "",
                content: record["content"] as? String ?? "",
                isPinned: record["isPinned"] as? Bool ?? false
            )
        }
    }
}

How to set up delta synchronization: step-by-step guide

  1. Create a subscription for record changes (CKQuerySubscription) — this enables silent push on every change.
    func setupSubscription() async throws {
        let predicate = NSPredicate(value: true)
        let subscription = CKQuerySubscription(
            recordType: "Note",
            predicate: predicate,
            subscriptionID: "notes-changes",
            options: [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]
        )
    
        let notificationInfo = CKSubscription.NotificationInfo()
        notificationInfo.shouldSendContentAvailable = true // silent push
        subscription.notificationInfo = notificationInfo
    
        try await privateDB.save(subscription)
    }
    
  2. Implement push notification handling in AppDelegate — on receiving a silent push, call fetchChanges().
    func application(_ application: UIApplication,
                     didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult {
        let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)
        if notification?.containerIdentifier == "iCloud.com.company.appname" {
            await cloudKitManager.fetchChanges()
            return .newData
        }
        return .noData
    }
    
  3. Use CKFetchRecordZoneChangesOperation with serverChangeToken — load only changed records.
    func fetchChanges() async throws {
        let zone = CKRecordZone(zoneName: "NotesZone")
        var config = CKFetchRecordZoneChangesOperation.ZoneConfiguration()
        config.previousServerChangeToken = UserDefaults.standard
            .data(forKey: "notesZoneChangeToken")
            .flatMap { try? NSKeyedUnarchiver.unarchivedObject(ofClass: CKServerChangeToken.self, from: $0) }
    
        let operation = CKFetchRecordZoneChangesOperation(
            recordZoneIDs: [zone.zoneID],
            configurationsByRecordZoneID: [zone.zoneID: config]
        )
    
        operation.recordWasChangedBlock = { _, result in
            guard let record = try? result.get() else { return }
            Task { await self.localStore.upsert(record) }
        }
    
        operation.recordWithIDWasDeletedBlock = { recordID, _ in
            Task { await self.localStore.delete(id: recordID.recordName) }
        }
    
        operation.recordZoneFetchResultBlock = { _, result in
            guard case .success(let info) = result else { return }
            // Save token for next delta sync
            if let tokenData = try? NSKeyedArchiver.archivedData(
                    withRootObject: info.newServerChangeToken, requiringSecureCoding: true) {
                UserDefaults.standard.set(tokenData, forKey: "notesZoneChangeToken")
            }
        }
    
        privateDB.add(operation)
    }
    

How to avoid conflicts during simultaneous editing?

CloudKit does not resolve conflicts automatically for Custom Zones. When saving to an existing recordID, if the recordChangeTag does not match, you get a serverRecordChanged error. Manual merge is required. We use a last-writer-wins strategy or three-way merge. Here's a conflict handler:

// In the save block of CKModifyRecordsOperation
operation.perRecordSaveBlock = { recordID, saveResult in
    if case .failure(let error) = saveResult {
        if let ckError = error as? CKError, ckError.code == .serverRecordChanged {
            let serverRecord = ckError.userInfo[CKRecordChangedErrorServerRecordKey] as! CKRecord
            let clientRecord = ckError.userInfo[CKRecordChangedErrorClientRecordKey] as! CKRecord
            // Resolve conflict: take the latest version
            serverRecord["modifiedAt"] = Date()
            operation.recordsToSave = [serverRecord]
        }
    }
}
Common CloudKit sync issues
  • CKError.accountTemporarilyUnavailable: user signed out of iCloud or disabled sync for the app. Handle gracefully — don't crash, suggest log in or work locally.
  • Network quota exceeded: too frequent requests to CloudKit. Use subscriptions + delta sync instead of polling.
  • Conflicts during simultaneous editing. Resolve with manual merge as described above.

What's included in the work

Stage Duration Result
Requirements analysis and architecture selection 1–2 days Technical specification, data schema
CloudKit database design 1–2 days Record models, indexes, subscriptions
Sync implementation (iOS) 5–10 days Code with CloudKit integration, conflict handling
Push notification setup 1 day Silent push for background sync
Testing on multiple devices 2–3 days Load testing, bug fixes
Deployment and monitoring 1 day CloudKit console access, error dashboard

Timeline: from 2 to 4 weeks. Cost is calculated individually. Get a consultation — we'll evaluate your project in one day. Contact us to discuss details.

We have been doing iOS development for over 10 years, implemented 30+ projects with CloudKit sync. We guarantee seamless synchronization between devices within 24 hours after deployment. Order CloudKit integration today and get rid of sync issues.

Apple CloudKit Documentation

How to Choose a Local Data Storage Solution (Room, Core Data, Realm, Isar)?

We've all seen the scenario: the app loses data when the network drops — and it's not just a bug, it's a failure of the use case. The user fills out a form, taps "Submit", gets a timeout, and loses everything. Or worse: data gets sent twice due to incorrect retry logic. A properly chosen and configured storage layer solves this problem once and for all. The wrong choice can cost teams months of rewriting code and up to 70% of time spent on synchronization. Our experience — 10+ years in mobile development, over 50 projects with offline storage — confirms: the storage choice determines 80% of future performance and synchronization issues.

In practice, storage selection is driven by two factors: data type and synchronization requirements, not library popularity.

Room (Android) — a wrapper over SQLite with compile-time verification of SQL queries. If a query is invalid, the build fails — better than a SQLiteException at runtime. Room integrates well with Kotlin Flow and LiveData, making reactive UI updates straightforward. The main challenge is schema migrations. @Database(version = N, exportSchema = true) with migration files in assets/databases/ is mandatory; otherwise, fallbackToDestructiveMigration() will simply delete the user's data on app update.

Core Data (iOS) — not a database, but an object graph management framework over SQLite (or XML, or in-memory). NSPersistentContainer with viewContext for reading on the main thread and newBackgroundContext() for writing is the basic setup. The trouble begins when a developer calls save() on viewContext from a background thread: EXC_BAD_ACCESS at a random moment, happens once a week, with almost nothing useful in the crash log. You must use performAndWait or perform for each context strictly on its own thread. Apple Core Data Programming Guide recommends this approach.

Realm wins where you need speed with large object sets and built-in reactivity through Results + observe(). Realm stores objects directly without ORM mapping, so reads require no deserialization. According to our measurements, Realm processes reads 2–3 times faster than Core Data for volumes over 10,000 objects. On Flutter, the Realm SDK (ex-MongoDB Realm) supports Device Sync — but that's a managed service with separate infrastructure.

Hive and Isar are Flutter-specific solutions. Hive is a key-value store, fast, simple, suitable for settings and caches. Isar is a full document-oriented database with indexes, written in Rust, compiled to native code. For Flutter apps with offline functionality, Isar is now preferred: built-in query builder with type-safe filters, transactions, watchObject/watchQuery for reactivity.

Platform Solution Reactivity Synchronization
Android Room + Flow LiveData/Flow WorkManager
iOS Core Data NSFetchedResultsController CloudKit
Flutter Isar Streams Custom / Realm Sync
Cross-platform Realm RealmResults.observe Device Sync
Flutter (simple) Hive ValueListenable None

Contact us for a free audit of your current storage and optimization recommendations — this will save you hundreds of development hours and up to 60% of server request traffic.

Why Is Offline Synchronization the Hardest Part?

Local storage itself is not complicated. The complexity lies in synchronizing with the server in the presence of conflicts.

The most common pattern is optimistic updates with rollback. The user edits a record, the UI reflects the change instantly, a background request goes to the server. If the server returns an error, we roll back the local state. Sounds simple. In practice: if the user has left the screen and returned before the rollback (which may take 3 seconds), the UX is broken. You need an explicit operation queue with states (PENDING, SYNCED, FAILED) in a separate table.

On Android, for background synchronization we use WorkManager with Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED). Don't forget setInputMerger(ArrayCreatingInputMerger::class) when batching tasks — otherwise, concurrent runs will overwrite data. A typical operation queue implementation:

class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        val pendingOps = syncDao.getPendingOperations()
        for (op in pendingOps) {
            try {
                apiClient.send(op.payload)
                syncDao.markSynced(op.id)
            } catch (e: Exception) {
                syncDao.markFailed(op.id, e.message)
                return Result.retry()
            }
        }
        return Result.success()
    }
}

On iOS, the equivalent is BGTaskScheduler with BGProcessingTaskRequest. iOS limitations on background execution time (~30 seconds for refresh tasks) mean that synchronization must be incremental: not "sync everything," but "sync the next N records, save the cursor."

Conflicts in multi-device scenarios are resolved with one of three approaches:

  • Last-write-wins based on updated_at (simplest, loses data on concurrent edits)
  • Server-wins (client always accepts server version)
  • Three-way merge (complex, requires a common ancestor — suitable for documents)

For most B2C apps, last-write-wins with a user-level time vector is sufficient, but for collaborative editing, a CRDTs approach is needed — then look at Automerge or Yjs with mobile bindings.

How We Build the Storage Layer

The repository pattern is not optional — it's mandatory. UserRepository doesn't know where the data comes from: Room, Realm, or network. The ViewModel calls repository.getUser(id), gets a Flow/Stream, and displays data. Caching logic resides inside the repository.

For Flutter, a typical architecture: Isar for persistence, Riverpod for state management, ConnectivityPlus for network status, and a custom SyncService with an operation queue. Riverpod's AsyncNotifier conveniently covers the logic of "show cache, update from network, show new data." Example repository with caching:

class UserRepository {
  final Isar isar;
  final ApiClient api;

  Future<User> getUser(String id) async {
    // try from local storage first
    final cached = await isar.user.where().idEqualTo(id).findFirst();
    if (cached != null) return cached;
    // otherwise from network
    final remote = await api.fetchUser(id);
    // save locally
    await isar.writeTxn(() => isar.user.put(remote));
    return remote;
  }
}

Another important topic is encryption. If the app stores medical data, payment cards, or corporate documents, SQLCipher (Android) and NSFileProtection (iOS) are not optional. Realm supports encryption natively via a 64-byte key that must be stored in Keychain/Keystore, not in SharedPreferences. Skimping on security can lead to data leaks with serious consequences.

What the Work Includes

We guarantee a transparent process and document each stage:

Stage Result
Requirements audit Document analyzing data types, volumes, synchronization scenarios
Schema design ER diagram, migration files, conflict resolution plan
Repository layer development Code with unit tests (in-memory DB + network mocks)
Synchronization integration Operation queue, error handling, fallback logic
Profiling and optimization Report from Android Profiler / Core Data SQLDebug, recommendations
Deployment and documentation Deployment instructions, API description, repository access

Want to avoid common mistakes when designing storage? Contact us — we'll help design a reliable local storage from scratch or improve an existing one.

Stages of Work

We start with a requirements audit: what data, what volume, is synchronization needed, are conflicts possible. At this stage, it becomes clear whether Core Data or an SQLite-based solution is needed, whether Realm Sync is required or simple REST polling will suffice.

Next, we design the schema with migrations in mind. Schemas change in any project — the question is not "will there be migrations," but "how painful will they be." We export the schema as JSON, store it in the repository, and write tests for each version's migration.

Development includes unit test coverage for the repository layer: network layer mocks, a real in-memory database for query testing. Before release, we profile queries using Android Profiler (Database Inspector tab) or Core Data debug flags (-com.apple.CoreData.SQLDebug 1).

The implementation timeline for a storage layer with basic offline synchronization ranges from 2 to 6 weeks, depending on schema complexity and conflict resolution requirements. Contact us to get a consultation on choosing the optimal stack and migrations.