skip to content

With FileManager on iOS, how does a scanning app share its latest scan with its share extension, and what breaks if misconfigured?

level: middleimportance: should knowfreq 45%

answer

  1. two processes, two sandboxes
  2. an entitlement on both targets
  3. an identifier that starts with group.
  4. a method that can return nil
  5. only one Library subfolder is created for you

basics

~20 s

An app and its extension have separate sandboxes, so shared files live in an App Group container. Give both targets the same App Groups entitlement and call containerURL(forSecurityApplicationGroupIdentifier:), which returns nil on iOS for a wrong identifier.

solid answer

~40 s

The share extension is a separate process with its own sandbox, so it cannot see the app's `Documents`. Both targets join one App Group through the App Groups entitlement, with an identifier such as `group.com.example.scanner`, and both call `FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:)` to get the shared folder. On iOS that method returns `nil` when the identifier is not in the target's entitlement, so I guard instead of force-unwrapping. The system creates only `Library/Caches` inside the container, so I create any other folder myself, and I write the latest scan with `.atomic` so the extension never reads a half-written file. I never store the container's path: the system makes no promise about its location, so each process asks the method every time.

code

swift · 21 lines
swift
import Foundation

enum SharedScanError: Error { case appGroupUnavailable }

enum SharedScans {
    static let groupID = "group.com.example.scanner"

    static func latestScanURL() throws -> URL {
        guard let container = FileManager.default
            .containerURL(forSecurityApplicationGroupIdentifier: groupID) else {
            throw SharedScanError.appGroupUnavailable  // entitlement missing or ID misspelt
        }
        let dir = container.appending(path: "Library/Application Support/Shared", directoryHint: .isDirectory)
        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        return dir.appending(path: "latest.pdf")
    }

    static func publishLatest(_ pdf: Data) throws {
        try pdf.write(to: latestScanURL(), options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
    }
}

go deeper

for a junior

Recall that an extension has its own sandbox, that sharing goes through an App Group, and the name of the FileManager method that returns the group's folder.

for a middle

Explain the entitlement on both targets, the group. prefix, the nil return on iOS, which subfolder the system creates, and why the shared file is written atomically.

for a senior

Diagnose a nil container in one target only, plan the one-time migration of existing scans, and say when atomic writes stop being enough because both processes write.

for a principal

Decide what is shared at all: the smallest set of files the extension needs, one shared layout definition, and the protection class every shared file must use.

## Why the app's own folders are out of reach An app extension, such as a share extension, ships inside the app but runs as **its own process with its own sandbox container**. Its `URL.documentsDirectory` is the extension's Documents folder, not the app's, so a scan the app saved there is invisible to it. To share files on one device, apps and extensions from the same developer join an **App Group** and use the group's shared container. ## Setting it up 1. Add the **App Groups** capability to the app target and to the extension target, with the same identifier. On iOS the identifier starts with `group.` followed by the group name, such as `group.com.example.scanner`. 2. In each process, call `FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.example.scanner")`. The string must match one of the identifiers in that target's entitlement exactly. 3. Create the folders you need inside it. On iOS the system creates only `Library/Caches` in a new group container; any `Library/Application Support` or other folder is yours to create with `createDirectory(at:withIntermediateDirectories: true)`. 4. Write the shared file, and have the other process read it. ## What the method promises on iOS | Behaviour | iOS | macOS, for contrast | |---|---|---| | Identifier not in the entitlement | returns `nil` | returns a URL whose folder does not exist | | Folders created for you | `Library/Caches` only | `Library/Application Support`, `Library/Caches`, `Library/Preferences` | | Location of the folder | no guarantee; reachable only through the returned URL | under the user's Group Containers folder | | When every app in the group is deleted | the system removes the container | kept | The `nil` return is the iOS failure signal. A misspelt identifier, an entitlement added to only one target, or a provisioning profile that lacks the group can all show up as `nil`, so a force-unwrap turns a configuration slip into a launch crash in the extension. ## Writing a file two processes read - **Write atomically.** `data.write(to: url, options: .atomic)` writes an auxiliary file and swaps it in, so the extension sees either the previous scan or the new one, never a torn file. - **Agree on the layout.** Apple's documentation asks the group's apps to coordinate the container's structure among themselves; keep the folder names in one shared source file both targets compile. - **Pick the protection class on purpose.** The shared file follows the same data-protection rules as any other file, so a widget or extension that runs while the phone is locked can read only a file whose class allows it. - **Never persist the path.** Store names relative to the container and rebuild the URL from the method on each use. When both processes may write the same file at the same moment, plain atomic writes are no longer enough and the file needs coordinated access, which belongs with the iCloud and document-coordination material. Small settings the two share go through an App Group `UserDefaults` suite, covered with SwiftUI's defaults storage; this answer is about files. ## Reading the file in the extension The extension compiles the same helper and reads with `Data(contentsOf:)`. Until the app has published a first scan there is nothing to read, so a thrown `fileReadNoSuchFile` means "no scan yet" and the extension shows an empty state rather than an error. Giving each shared file **one writer** keeps things simple: the app writes `latest.pdf`, and the extension writes only into an inbox folder of its own, such as one for images the user shares into the scanner, which the app drains with `contentsOfDirectory(at:includingPropertiesForKeys:options:)` and `moveItem(at:to:)` on its next launch. ## Moving existing users' data An app that adds an extension late already has scans in its private `Documents`. A one-time migration on launch moves the files the extension needs with `moveItem(at:to:)` into the group container and records that it ran. Moving rather than copying avoids keeping two copies of the same PDF in two backed-up places. ## Failures in review - Reading `URL.documentsDirectory` in the extension and expecting the app's files. - Building the container path by hand from a path seen in a log. - The entitlement on the app target only. - `containerURL(...)!` in extension code. - Assuming `Library/Application Support` exists inside the group container. - A non-atomic write that the extension can read halfway through.

  • The extension's containerURL call returns nil in a TestFlight build but works in the app. What do you check?
    That the extension target itself carries the App Groups entitlement with the same `group.` identifier, and that its provisioning profile includes that group. The app working proves nothing about the extension: each target is signed with its own entitlements, and on iOS a group missing from the calling target's entitlement makes the method return `nil`.
  • What happens to the shared container when the user deletes the app?
    On iOS the system removes a group container once every app in the group has been removed from the device. If the developer has a second app in the same group that is still installed, the container and its files remain, which is why shared files should never be treated as the deleted app's private data.

  • Expecting the share extension to read the app's own Documents folder
  • Building the group container path by hand instead of calling containerURL
  • Force-unwrapping the result of containerURL(forSecurityApplicationGroupIdentifier:)
  • Adding the App Groups entitlement to the app target only
  • Assuming Library/Application Support already exists inside the group container