Sharing Flow

Complete technical breakdown of CloudKit sharing in TheCompanyApp.

Share Creation (Owner)

Step 1: Initiate Share

User Action: Settings → Share Company → Tap "Share" button

Code (ChoosVersionView.swift):

func createCKShareIfNeeded() async {
    let company = selectedCompany
    
    // Check for existing share
    let shares = try? container.fetchShares(matching: [company.objectID])
    if let existing = shares?[company.objectID] {
        presentShareController(with: existing)
        return
    }
    
    // Create new share
    let (_, share) = try await container.share([company], to: nil)
    
    // Enlist all company data
    await enlistAllCompanyData(company, into: share)
    
    presentShareController(with: share)
}

All existing company data must be enlisted:

Why: CloudKit shares work via zones. All records in the zone are accessible to participants.

Step 3: Present Share UI

iOS presents standard CloudKit sharing sheet.

Step 4: Generate Share URL

CloudKit generates URL:

Owner copies and sends via Messages/Email.

Share Acceptance (Participant)

Step 1: Open Share URL

Participant taps link → Safari opens → Redirects to app (universal link)

App Receives URL (ContentView.swift):

Step 2: Extract Metadata

Step 3: Accept Share

CloudKit Actions:

  1. Adds share to participant's Shared Database

  2. Creates zone for this share

  3. Populates zone with records from owner's share

  4. Returns acceptance confirmation

Step 4: Sync to Shared Store

Automatic:

  • Core Data's CloudKit integration detects new records in Shared Database

  • Downloads records

  • Saves to Shared Store (TheCompanyApp-shared.sqlite)

  • Company appears in companies list

Timing: 5-60 seconds depending on data size.

Ongoing Sync

New Data (Owner Creates)

Flow:

  1. Save to Private Store

  2. CloudKit exports to Private Database

  3. CKShare zone gets updated (item added)

  4. CloudKit pushes update to Shared Database

  5. Participants download from Shared Database → Shared Store

New Data (Participant Creates)

Flow:

  1. Save to Shared Store

  2. CloudKit exports to Shared Database (in share's zone)

  3. Owner and other participants poll Shared Database

  4. Download new order

Removing Participants

Owner Action: Settings → Sharing → Tap participant → Remove

Code:

Effect:

  • Participant loses access to share

  • CloudKit removes participant from share

  • Participant's device deletes records on next sync

Stopping Sharing

Owner Action: Settings → Stop Sharing

Code:

Effect:

  • CKShare deleted

  • All participants lose access

  • Company reverts to owner-only (Private Store)

  • Can re-share later (creates new CKShare)


Related: Sync Architecture, Ownership Rules, Shared Store

Last updated