CloudKit Samples: Private Sync with Subscriptions and Push

Overview

CloudKit Samples: Private Sync with Subscriptions and Push

Goals

This project demonstrates using CloudKit Database Subscriptions and push notifications to keep two separate instances of an app in sync. Ideally it is run on both a simulator and a real device, and content changes made on the simulator are received and reflected on the device via CloudKit Subscriptions, similar to the functionality of the Notes or Photos apps.

Prerequisites

  • A Mac with Xcode 12 (or later) installed is required to build and test this project.
  • An iOS device which will receive CloudKit change notifications is required to install and run the app on.
  • An active Apple Developer Program membership is needed to create a CloudKit container and sign the app to run on a device.

Note: Simulators cannot register for remote push notifications. Running this sample on a device is required to receive CKSubscription push notifications and observe syncing functionality.

Setup Instructions

  1. Ensure you are logged into your developer account in Xcode with an active membership.
  2. In the “Signing & Capabilities” tab of the PrivateSync target, ensure your team is selected in the Signing section, and there is a valid container selected under the “iCloud” section.
  3. Ensure that both the simulator you wish to use and the device you will run the app on are logged into the same iCloud account.

Using Your Own iCloud Container

  • Create a new iCloud container through Xcode’s “Signing & Capabilities” tab of the PrivateSync app target.
  • Update the containerIdentifier property in Config.swift with your new iCloud container identifier.

How it Works

  • On first launch, the app creates a custom zone on the Private Database named “Contacts”, and subscribes to all record changes on that zone.
  • When running on a device, the app also registers with APNs (Apple Push Notification service), which is the mechanism for receiving information about changes through the aforementioned subscription.
  • After this initialization process, the app fetches the latest changes from the server, using a change token representing the last time changes were fetched and processed if available. On first launch, no local token is available, so all records are returned, and the token returned from this operation is saved.
  • The app’s main UI displays a list of Contacts. When the user adds a new Contact through the UI, a new record is created and saved to the database, and if successful, also saves this to a local store. This will trigger the UI to update and include the new Contact on the main list view.
  • Creating a new record triggers a notification to other devices which are registered for push notifications with the app through the CKRecordZoneSubscription created on first launch.
  • Devices receiving this notification will react by fetching the latest changes on the zone using the last known change token, and receive only the set of records that have changed since that change token was received. The records are updated locally and the UI now reflects the latest database state once again.

Example Flow

  1. Run the app on a device. Latest changes are fetched and a change token is stored.
  2. Repeat the above on a simulator, and add a new contact through the UI.
  3. The device receives a background push notification flagging that a change has occurred.
  4. The device fetches the changes, passing along the change token received in step 1. Only the new contact added in step 2 is returned and processed, and now shows on the UI.

Things To Learn

  • Creating a custom CloudKit Record Zone.
  • Creating a CloudKit Subscription that listens to database changes and sends a content-available push notification on change events.
  • Registering for push notifications with a SwiftUI-compatible UIApplicationDelegate class.
  • Receiving and handling a CKNotification.
  • Using a cached CKServerChangeToken to fetch only record changes and deletions since the last sync.
  • Adding, removing, and merging remote changes into a local cache, and reflecting those changes live in a UI.

Further Reading

You might also like...
This To-Do app was developed using Swift and SwiftUI and works on iOS, MacOS (Apple Silicon) and WatchOS. The tasks are kept on storage even when the app is restarted.

ToDo-SwiftUI This app has a lot of sentimental value for me, given that it helped me a lot to understand the process of doing an iOS app and became th

KHabit an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more.

an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more. The app is completely open source, it does not contain in-app or ads, and does not track the user in any way.

iOS app that detects LaTeX symbols from drawings. Built using PencilKit, SwiftUI, Combine and CoreML for iOS 14 and macOS 11.

DeTeXt Finding the symbol you want to use in LaTeX can be hard since you can't memorize all the possible commands and packages for every symbol you mi

an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more.

KHabit an open source, pure and minimalistic app which helps you maintain productive habits, and nothing more. The app is completely open source, it d

🎮 Favorite your games filter and see the upcoming games and ! Swift + Combine = 💜 Hacktoberfest 🎃 👾
🎮 Favorite your games filter and see the upcoming games and ! Swift + Combine = 💜 Hacktoberfest 🎃 👾

✨ Revill is App to list games and search best games ✨ Design in Swift UI + Combine ✨ The idea is develop this app in Hacktober Fest Expected To Do Des

Native and encrypted password manager for iOS and macOS.
Native and encrypted password manager for iOS and macOS.

Open Sesame Native and encrypted password manager for iOS and macOS. What is it? OpenSesame is a free and powerful password manager that lets you mana

SwiftUI iOS Widget and WatchOS app that randomly shows a word of the day with description and example.
SwiftUI iOS Widget and WatchOS app that randomly shows a word of the day with description and example.

Word Of The Day iOS Widget and WatchOS app made in SwiftUI that displays a random word of the day with description and example of usuage. Requirements

A SwiftUI implementation of React Hooks. Enhances reusability of stateful logic and gives state and lifecycle to function view.

SwiftUI Hooks A SwiftUI implementation of React Hooks. Enhances reusability of stateful logic and gives state and lifecycle to function view. Introduc

iOS App to display game lists and details with the ability to add games to your favorites list and see metacritic ratings.
iOS App to display game lists and details with the ability to add games to your favorites list and see metacritic ratings.

Game Data System - GDS Author: Heitor Silveira ([email protected]) iOS App to view games from various platforms, their description, release

Owner
null
A tiny app that will check your recent subscriptions on RevenueCat and will

Meow Let your RevenueCat talk Download Credits Big thanks to: RxSwift KeychainAccess Popover Notice of Non-Affiliation and Disclaimer We are not affil

2Stable 22 Jul 14, 2022
Sync your app's time with server's UTC time

ServerSync for iOS Apps Sometimes your app can't rely on the device's date and time settings being correct. This library will help you calibrate your

null 10 Dec 16, 2021
CloudKit -Core Data todo example

Todo CloudKit - Core Data example This the demo project for the 4-Dec-2021 meeting for a flock of swifts show casing a number of new language and SDK

Joshua Homann 4 Jul 14, 2022
COVID Safe Paths (based on Private Kit) is an open and privacy preserving system to use personal information to battle COVID

COVID Safe Paths is a mobile app for digital contract tracing (DCT) sponsored by Path Check a nonprofit and developed by a growing global community of engineers, designers, and contributors. Safe Paths is based on research originally conducted at the MIT Media Lab.

PathCheck Foundation 470 Nov 6, 2022
A SwiftUI iOS App and Vapor Server to send push notifications fueled by Siri Shortcuts.

Puffery An iOS App written in SwiftUI to send push notifications fueled by Siri Shortcuts. You can follow other's channels and directly receive update

Valentin Knabel 29 Oct 17, 2022
Warning pushNotification - Using push notification with Firebase Cloud Messaging

재난문자 푸시 알림 구현 1) 구현 기능 2) 기본 개념 (1) Remote Notification 불시에 발생한 업데이트 불특정 시간 예측 불

null 0 Jan 24, 2022
Swush - macOS Application to play with the Apple Push Notification service (APNs)

Swush ✨ Description A macOS app to push notifications to APNS with ease. ⚡ ?? Pe

Quentin Eude 80 Dec 23, 2022
In this mini app covered the concepts like basics of SwiftUI and Navigations and Animations and List with CRUD functions and MVVM and App Launch and App icons adding and also applied persistence using UserDefaults Concept.

TodoList In this application used the concepts from the beginner level project of SwiftUI_Evolve_1 The following concepts covered in this mini app Swi

Sivaram Yadav 2 Dec 4, 2021
Mahmoud-Abdelwahab 5 Nov 23, 2022
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

Gabriel Denoni 11 Dec 27, 2021