icloud_storage_plus 4.4.0
icloud_storage_plus: ^4.4.0 copied to clipboard
Flutter plugin for local iCloud Drive file operations with coordinated iOS and macOS access.
iCloud Storage Plus #
Flutter plugin for local file access inside an iCloud Drive ubiquity container on iOS and macOS, with coordinated file operations and optional Files app visibility.
Hosted reference docs are available on DeepWiki: https://deepwiki.com/Jason-Holt-Digital/icloud_storage_plus
This package operates inside your app's local iCloud ubiquity container. Apple owns iCloud Drive sync, materialization, freshness, and document conflict behavior; this plugin performs local file operations against the container path.
What this plugin does, in plain words #
Your app gets its own folder in iCloud Drive, called the container. This plugin reads, writes, moves, copies, lists, and deletes files in that folder. Apple does the syncing: it uploads your changes, downloads changes from other devices, and decides when. The plugin never waits for a sync to finish and never reports "not synced yet" as an error.
The core of the plugin is storing and syncing documents through iCloud Drive.
It may grow to cover other iCloud features, such as the key-value store
(NSUbiquitousKeyValueStore). A separate library, the
CloudKit sync bridge, syncs records through CloudKit.
Platform support #
| Platform | Minimum version |
|---|---|
| iOS | 13.0 |
| macOS | 10.15 |
The CloudKit sync bridge requires iOS 17 or macOS 14.
Installation #
flutter pub add icloud_storage_plus
Swift Package Manager (optional) #
This plugin supports Flutter’s Swift Package Manager integration for iOS/macOS
projects (requires Flutter >= 3.24). To enable SwiftPM in your app:
flutter config --enable-swift-package-manager
Before you start (Xcode / entitlements) #
- Create an iCloud Container ID (example:
iCloud.com.yourapp.container) - Enable iCloud for your App ID and assign that container
- In Xcode → your target → Signing & Capabilities, add iCloud, select your container, and enable the services for the features you use:
| Feature | Xcode capability | Entitlements |
|---|---|---|
Document storage (ICloudStorage) |
iCloud → iCloud Documents | com.apple.developer.icloud-services containing CloudDocuments; com.apple.developer.icloud-container-identifiers and com.apple.developer.ubiquity-container-identifiers listing your container |
CloudKit sync bridge (CloudKitSyncEngine, CloudKitAssetStore) |
iCloud → CloudKit; Push Notifications; on iOS, Background Modes → Remote notifications | com.apple.developer.icloud-services containing CloudKit; com.apple.developer.icloud-container-identifiers listing your container; aps-environment (iOS) or com.apple.developer.aps-environment (macOS); on iOS, remote-notification in UIBackgroundModes in Info.plist |
An app that uses both features enables both services for the same container.
Files app integration (optional) #
To make items visible in the Files app under “iCloud Drive”, you typically need
to declare your container under NSUbiquitousContainers in your Info.plist.
Files are only visible in Files/iCloud Drive when they live under the
Documents/ prefix.
// Visible in Files app
relativePath: 'Documents/notes.txt'
// Outside the Files app Documents/ convention
relativePath: 'cache/notes.txt'
Note: your app’s folder won’t appear in Files/iCloud Drive until at least one
file exists under Documents/.
Choosing the right API #
There are five “tiers” of API in this plugin:
- Path-only transfers for large files (no bytes returned to Dart)
uploadFile(local → iCloud)downloadFile(iCloud → local)
- In-place content for small files (bytes/strings cross the platform
channel; loads full contents in memory)
readInPlace,readInPlaceBytesreadInPlaceBytesManyreads a list of files with one coordinated read and returns a map from each path to its bytes. Files that do not exist are left out of the map. See Reading many small files.writeInPlace,writeInPlaceBytes- Reads use a plain coordinated read (
NSFileCoordinator), not aUIDocument/NSDocument, so each read is cheap. - On iOS and macOS, existing-file writes stage the complete new content and
install it with
FileManager.replaceItemAtunder coordinated ordinary-write access. This preserves the destination relative path, but is not a crash-durability or watcher-delivery guarantee. - Conflict versions are not automatically resolved or deleted. iCloud Drive sync and document conflict behavior remain Apple's responsibility.
- Those file-write overwrite paths still reject an existing directory destination instead of replacing it.
- File management and queries
delete,move,copy,renamedocumentExists,getItemMetadata- On iOS and macOS, copying onto an existing destination uses staged, coordinated replacement rather than remove-then-copy behavior.
- Existing-destination
copy()replacement is file-only on iOS and macOS: existing directories are rejected instead of replaced. copy()can copy files or directories to new destinations. If you need to replace an existing directory tree, manage that directory explicitly rather than relying on overwrite replacement.
- Moving local items into iCloud
moveIntoContainermoves a local file or a whole directory into the container withFileManager.setUbiquitous(true, itemAt:destinationURL:). It is a move, not a copy: the local item is gone afterwards. It works offline, and iCloud uploads later. Missing parent directories are created with a coordinated write. The destination must not exist.moveOutOfContainerusessetUbiquitous(false, ...)to move an item back to a local path. This removes it from iCloud on every device, so use it to undo amoveIntoContainer, not to turn iCloud off for data other devices use. To keep the iCloud copy, usedownloadFile.createDirectorymakes a container directory, with a coordinated write.
- Container listing (two complementary approaches)
gather—NSMetadataQuery-based; can discover remote files and document promises and deliver updated metadata snapshots while subscribed. Update timing and coalescing are controlled by Apple; results remain eventually consistent after local mutations.listContents— FileManager-based; immediately consistent after local mutations; returns download/upload status via URL resource values; only sees files with a local representation (including iCloud placeholders)
On iOS and macOS, the plugin's file-system work runs off the app's main thread:
container lookup, reads, writes and uploads (including their checks before
writing), moves, existence and metadata checks, conflict version calls, and the
request that starts a download. A file-system call in the iCloud container can
wait for seconds while iCloud is busy, so running it on the main thread would
freeze the app. On iOS, the UIDocument objects that copy files in and out and
document change observation stay on the main thread, as UIKit requires. On
macOS, NSDocument writes run in the background and document change
observation starts on a background queue.
Migration notes for 4.0.0 #
readInPlaceandreadInPlaceBytesnow return non-nullableStringandUint8Listvalues. CatchICloudItemNotFoundExceptionwhen a missing item is an optional domain outcome.ICloudStoragePlatform.getItemMetadatanow returnsFuture<ICloudItemMetadata?>. Custom platform implementations and fakes should return the typed model instead of a raw channel map.- Every public
ICloudOperationExceptionsubtype can be constructed directly from normalized fields. ThePlatformExceptiontransport decoder is internal toMethodChannelICloudStorageand is not a public API. - Native success replies for every
Future<void>method-channel operation must benull. Non-null replies are typedpluginContractfailures.
Migration notes for 2.2.0 #
readInPlaceandreadInPlaceBytesno longer acceptidleTimeoutsorretryBackoff. Remove those named arguments from callers.- The former timeout, item-not-downloaded, and download-in-progress exception and transport-code APIs were removed. Normal iCloud Drive lifecycle state is no longer a plugin-owned error surface.
- On iOS and macOS,
copy()over an existing destination no longer reports plugin-owned readiness failures for non-current, not-downloaded, downloading, or conflicted iCloud metadata. It rejects existing directory destinations, then lets Foundation perform the local replacement and report any actual operation failure.
Quick start #
import 'dart:io';
import 'package:icloud_storage_plus/icloud_storage.dart';
const containerId = 'iCloud.com.yourapp.container';
const notesPath = 'Documents/notes.txt';
Future<void> example() async {
final available = await ICloudStorage.icloudAvailable();
if (!available) {
// Not signed into iCloud, iCloud Drive disabled, etc.
return;
}
// 1) Write a text file *in place* (recommended for JSON/text).
await ICloudStorage.writeInPlace(
containerId: containerId,
relativePath: notesPath,
contents: 'Hello from iCloud',
);
final contents = await ICloudStorage.readInPlace(
containerId: containerId,
relativePath: notesPath,
);
// 2) Copy-out to local storage (useful for large files / sharing / etc).
final localCopy = '${Directory.systemTemp.path}/notes.txt';
await ICloudStorage.downloadFile(
containerId: containerId,
relativePath: notesPath,
localPath: localCopy,
);
// 3) Typed metadata / listing.
final metadata = await ICloudStorage.getItemMetadata(
containerId: containerId,
relativePath: notesPath,
);
if (metadata != null && !metadata.isDirectory) {
final size = metadata.sizeInBytes;
}
try {
// Example: path validation happens in Dart before calling native.
await ICloudStorage.readInPlace(
containerId: containerId,
relativePath: 'Documents/.hidden.txt',
);
} on InvalidArgumentException catch (e) {
// Invalid path segment (starts with '.', contains ':', etc.).
throw Exception(e);
} on ICloudOperationException catch (e) {
// Native and method/event-channel failures are typed.
throw Exception(e);
}
}
Turning iCloud on or off in your app #
A common app setting is "Use iCloud". Here is the pattern Apple recommends, and the methods that do each step.
Turning iCloud on: move the files in. Call moveIntoContainer for each
local file or folder. It is a move, not a copy, so the local file is gone
afterwards and there is only one copy to keep track of. It works offline: the
move happens right away, and iCloud uploads the files when the device is back
online.
await ICloudStorage.moveIntoContainer(
containerId: containerId,
localPath: '/path/to/app/documents/journals', // absolute path
relativePath: 'Documents/journals',
);
Things to know:
- The destination must not exist yet. If iCloud already has an item with that name (for example from another device), decide in your app what to do: keep both, combine them, or replace one. Then move the rest.
- Missing parent folders in the container are created for you.
- Use
documentExiststo check whether the container already has an item. It returnstruefor folders too. - Use
listContentsto see what one container folder holds right now.
Turning iCloud off: copy the files out. Use downloadFile to copy each
file to local storage. (readInPlace returns a file's contents instead; save
them to a local file yourself.) This leaves the iCloud copy
in place, so other devices that still use iCloud keep their data.
Only use moveOutOfContainer to undo a moveIntoContainer that other devices
have not relied on yet. It removes the item from iCloud on every device.
Telling the user what is happening. listContents and getItemMetadata
report upload and download status from Apple. For example, a file that is on
this device but not uploaded yet (isUploaded == false) can be shown as
"Waiting to upload". Read the status when you show it; do not poll or wait for
it to change.
Watching document changes #
watchDocumentChanges observes an existing file. Create or load the document
before starting the watcher, attach a listener synchronously inside onChange,
then cancel the returned stream subscription when it is no longer needed.
import 'dart:async';
StreamSubscription<ICloudDocumentChange>? changeSubscription;
await ICloudStorage.watchDocumentChanges(
containerId: containerId,
relativePath: notesPath,
onChange: (changes) {
changeSubscription = changes.listen((change) async {
switch (change.kind) {
case ICloudDocumentChangeKind.invalidation:
// Treat this as an invalidation hint and reread coordinated state.
await ICloudStorage.readInPlace(
containerId: containerId,
relativePath: notesPath,
);
case ICloudDocumentChangeKind.conflict:
// Enumerate versions and apply your app's conflict policy.
break;
case ICloudDocumentChangeKind.savingError:
case ICloudDocumentChangeKind.editingDisabled:
break;
}
});
},
);
// Later, when this document is no longer observed:
await changeSubscription?.cancel();
Each call provides one single-subscription stream. Multiple calls may observe the same path independently. Treat every event as an invalidation hint and reread the current local file or metadata:
- Apple may delay, coalesce, omit, or repeat native callbacks.
invalidationdoes not claim that another device originated the change.- On macOS, non-conflict callbacks with the same on-disk modification date are suppressed. Conflict callbacks bypass that filter and may repeat.
- A successful plugin write to an existing watched macOS file records the resulting modification date so a matching queued callback is suppressed. This does not apply to iOS, creation, other processes, or arbitrary writes.
- Watching a path that does not yet exist is unsupported. Create or materialize the item before starting the watcher.
Conflict events are explicit and app-owned—the plugin never selects or deletes conflict versions automatically. iCloud Drive owns cross-device propagation and does not provide a real-time latency guarantee. This watcher reports changes after Foundation delivers them; it is not a Google Docs-style collaboration channel.
Transfers with progress #
Progress and successful completion are delivered as data events of type
ICloudTransferProgress. Failures are delivered through stream onError as
typed ICloudOperationException values.
Important: attach a listener synchronously inside the onProgress callback.
Delayed or ignored streams are rejected before native event-channel allocation.
Canceling that listener stops progress observation; it does not cancel the file
transfer. If the listener is paused when a native transfer failure arrives, or
canceled before failure delivery, the returned transfer Future completes with
the typed error
instead so the failure is not lost.
await ICloudStorage.uploadFile(
containerId: containerId,
localPath: '/absolute/path/to/local/file.pdf',
relativePath: 'Documents/file.pdf',
onProgress: (stream) {
stream.listen(
(event) {
if (event.isProgress) {
// 0.0 - 100.0
final percent = event.percent!;
} else if (event.isDone) {
// Transfer completed successfully.
}
},
onError: (Object error) {
final exception = error as ICloudOperationException;
},
);
},
);
Reading many small files #
readInPlaceBytesMany reads many files in one call. It coordinates all of them
together, which is much faster than calling readInPlaceBytes once per file
when you copy a folder of small documents.
final contents = await ICloudStorage.readInPlaceBytesMany(
containerId: containerId,
relativePaths: [
'Documents/journal/index.json',
'Documents/journal/entry-1.json',
'Documents/journal/entry-2.json',
],
);
// Keys are the paths exactly as you passed them.
// A path with no file is not in the map, so this is null when it is missing.
final Uint8List? index = contents['Documents/journal/index.json'];
- The result has an entry only for files that exist. A missing file is not an error.
- Any other failure (for example a path that is a folder, no permission, or a
failed coordinated read) fails the whole call with the same
ICloudOperationExceptiontypesreadInPlaceBytesthrows. When the failure belongs to one file, the exception'srelativePathnames it. - Each path is checked like
readInPlaceByteschecks its path. An invalid path throwsInvalidArgumentExceptionbefore anything is read. - An empty list returns an empty map.
- Every file is loaded into memory at once, so use it for small files.
Container-relative paths #
This plugin consistently uses relativePath for paths inside the iCloud
container, including uploadFile and downloadFile.
Trailing slashes #
Directory paths can show up with trailing slashes in metadata, so the directory-oriented methods accept them:
delete,move,copy,rename,documentExists,getItemMetadata
File-centric operations reject trailing slashes (they require a file path):
uploadFile,downloadFilereadInPlace,readInPlaceBytes,readInPlaceBytesMany,writeInPlace,writeInPlaceBytes
On iOS and macOS, file-centric overwrite operations reject an existing directory
destination instead of replacing it. Existing-destination copy() replacement
does the same; copy() can still copy a directory when the destination does not
already exist.
Path validation #
Many methods validate path segments in Dart and throw InvalidArgumentException
for invalid values (empty segments, segments starting with ., segments that
contain : or /, etc).
Listing / watching with gather #
gather() returns a GatherResult whose files field contains the complete
metadata snapshot. If any native entry is malformed, the initial call or update
stream fails with a typed plugin-contract exception; partial snapshots are never
returned.
When onUpdate is provided, attach a listener synchronously inside the
callback. Delayed or ignored streams are rejected before native event-channel
allocation. The update stream stays active until the subscription is canceled.
final initial = await ICloudStorage.gather(
containerId: containerId,
onUpdate: (stream) {
stream.listen((update) {
// Full file list on every update.
final files = update.files;
});
},
);
Immediate listing with listContents #
listContents() returns List<ContainerItem> — an immediately-consistent
snapshot of the container (or a subdirectory) using FileManager rather than
NSMetadataQuery.
final items = await ICloudStorage.listContents(
containerId: containerId,
relativePath: 'Documents/', // optional; defaults to container root
);
for (final item in items) {
print('${item.relativePath} — ${item.downloadStatus}');
if (item.isDirectory) print(' (directory)');
if (item.hasUnresolvedConflicts) print(' ⚠ conflicts');
}
gather vs listContents #
| Capability | gather |
listContents |
|---|---|---|
| Consistency after mutations | Eventually consistent (Spotlight index lag) | Immediately consistent |
| Sees remote-only files | Yes (document promises) | No |
| Ongoing update stream | Yes; best-effort metadata snapshots with Apple-controlled timing/coalescing | No (one-shot) |
| Download/upload progress % | Yes | No |
| Download/upload status | Yes | Yes |
| Conflict detection | Yes | Yes |
Hidden files (.DS_Store, etc.) |
Excluded by Spotlight | Filtered by resolved-name prefix |
| Underlying mechanism | NSMetadataQuery (Spotlight) |
FileManager + URL resource values |
When to use which:
- After your own mutations (rename, delete, copy, write): use
listContentsfor an immediate, accurate listing. - Initial sync on a new device: use
gatherto discover document promises (remote files not yet represented locally). - Container-wide refresh hints: use
gatherwithonUpdate. Treat each update as a reason to refresh metadata; timing, coalescing, and origin are not guaranteed.
iCloud placeholder files #
iCloud uses placeholder files to represent items that exist in iCloud but have not been fully downloaded to the local device. There are two eras:
- iOS and pre-Sonoma macOS: stub files named
.originalName.icloud(~192 bytes) that stand in for the real file. - macOS Sonoma+: APFS dataless files that keep the real filename and logical size; the actual content is fetched on demand.
Both gather and listContents handle this transparently — they resolve
placeholder names and report download status so you don't need to parse
.icloud filenames yourself.
listContents also filters out system hidden files (.DS_Store, .Trash,
.DocumentRevisions-V100, etc.) by skipping any entry whose resolved name
starts with .. Files whose real name starts with . will not appear in
listContents results. gather excludes most of these naturally via
Spotlight's indexing scope.
To check if a file has local content available:
// With ContainerItem (from listContents)
if (item.isDownloaded) {
// File has local content (downloadStatus is .downloaded or .current)
}
// With ICloudFile (from gather)
if (file.downloadStatus == DownloadStatus.current) {
// Fully up-to-date local copy
}
Metadata models #
ICloudItemMetadata (from getItemMetadata) #
Populated from the known-path metadata request API. This is the typed metadata model for request/response use.
class ICloudItemMetadata {
final String relativePath;
final bool isDirectory;
final int? sizeInBytes;
final DateTime? creationDate;
final DateTime? contentChangeDate;
final bool isDownloading;
final DownloadStatus? downloadStatus;
final bool isUploading;
final bool isUploaded;
final bool hasUnresolvedConflicts;
/// Whether the item has local content available.
// bool get isLocal => <computed>;
}
ICloudFile (from gather) #
Populated from NSMetadataQuery. Eventually consistent — the Spotlight index
may lag behind local filesystem mutations.
class ICloudFile {
final String relativePath;
final bool isDirectory;
final int? sizeInBytes;
final DateTime? creationDate;
final DateTime? contentChangeDate;
final bool isDownloading;
final DownloadStatus? downloadStatus;
final bool isUploading;
final bool isUploaded;
final bool hasUnresolvedConflicts;
}
ContainerItem (from listContents) #
Populated from FileManager.contentsOfDirectory with URL resource values.
Immediately consistent after local mutations.
class ContainerItem {
final String relativePath;
final bool isDirectory;
final DownloadStatus? downloadStatus;
final bool isDownloading;
final bool isUploaded;
final bool isUploading;
final bool hasUnresolvedConflicts;
/// Whether the item has local content available.
// bool get isDownloaded => <computed>;
}
ContainerItem does not include sizeInBytes, creationDate, or
contentChangeDate — these require NSMetadataQuery or additional URL resource
key lookups that are not part of the current implementation.
Error handling #
Dart-side validation (InvalidArgumentException) #
Thrown when you pass an invalid path/name to the Dart API, or when a stream callback returns without attaching a listener synchronously. These failures occur before native allocation.
Native and channel failures (ICloudOperationException) #
Native method-channel failures, event-channel failures, and malformed channel
payloads map to typed exceptions. This applies to request/response APIs such as
icloudAvailable, readInPlace, readInPlaceBytesMany, writeInPlace, copy,
getContainerPath, and getItemMetadata, plus gather, document-change, and transfer streams:
ICloudContainerAccessExceptionICloudItemNotFoundExceptionICloudConflictExceptionICloudCoordinationExceptionICloudInvalidArgumentExceptionICloudCancelledExceptionICloudInitializationExceptionICloudUnknownNativeException- Direct
ICloudOperationExceptionvalues forpluginContractfailures or native categories introduced after this package version
For iOS and macOS file-write overwrite operations, trying to overwrite an existing directory target is treated as an invalid argument rather than as a successful replacement.
These exceptions expose operation, retryable, relativePath, and native
error context when the platform provides it. ICloudCancelledException reports
native operation cancellation; ICloudInitializationException reports a native
plugin or event-channel initialization failure.
ICloudCoordinationException is reserved for structured coordination failures.
Current iOS and macOS native implementations still classify some lower-level
coordination problems as ICloudUnknownNativeException when they do not yet
emit an explicit coordination category.
Normal iCloud Drive lifecycle states such as not-current, not-downloaded, or downloading are not typed plugin exceptions. Metadata APIs can still report those states as metadata, but request/response operations no longer manufacture timeout/readiness failures from them.
CloudKit sync bridge #
package:icloud_storage_plus/cloudkit_sync.dart is a separate library that
wraps Apple's
CKSyncEngine
for the CloudKit private database. It requires iOS 17 or macOS 14; on older
versions every call throws a CloudKitSyncException with the code
unsupportedPlatformVersion. It uses CloudKit only and never touches the iCloud
Drive container, and it shares no code or state with document storage.
CKSyncEngine schedules fetches and sends, retries failures, pages through
changes, and listens for push notifications and account changes. Your app makes
every sync decision: what to send, how to apply fetched records, how to resolve
conflicts, and what to do when the account changes or a zone is deleted.
import 'package:icloud_storage_plus/cloudkit_sync.dart';
/// Connects the engine to the app's own storage, declared at the end.
abstract class LibrarySync implements CloudKitSyncDelegate {
final engine = const CloudKitSyncEngine('iCloud.com.yourapp.container');
Future<void> start() async => engine.start(
delegate: this,
stateSerialization: await loadEngineState(),
excludedZoneNames: ['Blobs'],
);
Future<void> bookChanged(String bookId) =>
engine.addPendingRecordZoneChanges([
CloudKitPendingRecordSave(
CloudKitRecordId(zoneName: 'Library', recordName: bookId),
),
]);
@override
Future<void> handleEvent(CloudKitSyncEvent event) async {
switch (event) {
case CloudKitStateUpdate(:final stateSerialization):
// Save it after the changes it covers; pass it to the next start.
await saveEngineState(stateSerialization);
case CloudKitFetchedRecordZoneChanges():
await applyServerChanges(event);
case CloudKitSentRecordZoneChanges():
// Keep each saved record's systemFields, and resolve failures such
// as CloudKitErrorCode.serverRecordChanged.
await handleSentChanges(event);
default:
break;
}
}
@override
Future<CloudKitRecordZoneChangeBatch?> nextRecordZoneChangeBatch(
List<CloudKitPendingRecordZoneChange> pendingChanges,
) async =>
CloudKitRecordZoneChangeBatch(
recordsToSave: [
for (final change in pendingChanges)
if (change is CloudKitPendingRecordSave) await recordFor(change.id),
],
recordIdsToDelete: [
for (final change in pendingChanges)
if (change is CloudKitPendingRecordDelete) change.id,
],
);
Future<String?> loadEngineState();
Future<void> saveEngineState(String stateSerialization);
Future<void> applyServerChanges(CloudKitFetchedRecordZoneChanges changes);
Future<void> handleSentChanges(CloudKitSentRecordZoneChanges changes);
/// Builds the record from local data, with the systemFields of its last
/// server copy.
Future<CloudKitRecord> recordFor(CloudKitRecordId id);
}
How the bridge behaves:
- The engine delivers one event at a time and waits for
handleEventto finish before the next. IfhandleEventthrows, the engine stops so the unhandled changes are delivered again after the nextstart. Later calls throwCloudKitSyncException.engineNotRunningwith the reason. nextRecordZoneChangeBatchreceives up to 250 pending changes. Returning null or an empty batch ends the send; the changes stay pending. If it throws, the send ends the same way and the error goes toFlutterError.reportError. For a change whose record no longer exists locally, callremovePendingRecordZoneChanges. If the native side cannot read the returned batch, the engine stops and later calls throwengineNotRunningwith the reason.- Record fields hold
String,int,double,Uint8List, or lists of those. A received record with any other field type, such as a date, a boolean, a reference, or a location, stops the engine. Later calls throwengineNotRunningwith a message naming the record type, record, and field, and the engine stops again after each start until that record is fixed. - Files travel as
assets. A received asset file belongs to CloudKit, so copy it beforehandleEventreturns. A received asset is null when CloudKit did not download it, as for theserverRecordof aserverRecordChangederror. Asset source and destination paths must be in the app's own container, not the iCloud Drive container; the bridge does not coordinate file access. - The app runs one engine at a time. Starting an engine replaces the running one.
accountStatus()returns the container'sCKContainer.accountStatus()as aCloudKitAccountStatus, whether or not the engine is running. Use it to tell a signed-out device from a restricted or temporarily unavailable account;CloudKitAccountChangeevents report later changes.- Failures throw
CloudKitSyncException. FornativeError,nativeDomainandnativeCodekeep the original CloudKit error.CloudKitErrorCodenames the codes apps usually act on, includingquotaExceeded; compare other codes with theirCKError.Coderaw values. - The example app is not set up for CloudKit, so it does not exercise the bridge.
Large files in a separate zone #
Every record in a zone the engine syncs is downloaded to every device,
including its assets. For large files that a device should download only when
the user opens them, such as book PDFs, keep the records in their own zone, pass
that zone in excludedZoneNames, and move each file with CloudKitAssetStore:
const store = CloudKitAssetStore('iCloud.com.yourapp.container');
const id = CloudKitRecordId(zoneName: 'Blobs', recordName: 'sha256-of-file');
if (!await store.recordExists(id)) {
await store.uploadAsset(
id: id,
recordType: 'Blob',
field: 'data',
source: pdf,
);
}
await store.downloadAsset(
id: id,
field: 'data',
destination: localFile,
onProgress: (fraction) => print('${(fraction * 100).round()}%'),
);
An excluded zone stays marked as needing a fetch, and the engine does not send
pending changes for it. Delete a file's record with store.deleteRecord(id)
instead of through the engine. A record that is
already gone counts as deleted.
Before releasing, deploy your CloudKit schema from the development environment to production in the CloudKit Console.
Troubleshooting / gotchas #
- Prefer testing on physical devices. iCloud sync is unreliable in iOS Simulator.
documentExists()checks the filesystem path in the container; it does not force a download.- If Files app visibility matters, ensure paths start with
Documents/and your container is configured underNSUbiquitousContainers. - After a rename/move/delete,
gather()may still return stale results for a few seconds while the Spotlight index catches up. UselistContents()for immediate consistency. moveIntoContainerfails if the destination already exists. Check withdocumentExistsfirst and decide what your app should do with both copies.- An item that is not in iCloud yet (for example a file a write is about to create) is not an error. The plugin only asks iCloud to download items that iCloud has.
Documentation #
- Hosted DeepWiki reference: https://deepwiki.com/Jason-Holt-Digital/icloud_storage_plus
- Local notes index:
doc/README.md
License #
MIT License - see LICENSE.
Credits #
Forked from icloud_storage by deansyd.
Upstream is referenced for attribution only. This repository is not intended to track upstream changes.