Cancel An NSItemProvider Load Without Resuming Twice
An import starts, the user cancels it, and the callback arrives anyway. If cancellation and the callback both resume the same continuation, the app has a new problem to display instead of the imported text.
A second callback does not get a second vote.
We’ll wrap one NSItemProvider data load with an explicit rule: the first terminal outcome accepted under a lock wins. If cancellation wins, release the waiting task and request cancellation through the provider’s Progress. If that handle hasn’t arrived yet, remember the request until it does.
This is a useful application of Swift 6.4’s noncopyable Continuation. The complete example requires iOS 27 or macOS 27, Swift 6.4, and Swift 6 language mode. It was checked with the installed Xcode 27.2 Release Candidate, build 27B48, and Swift 6.4.2. The downloadable project includes the exact code and executable checks.
Start with the right kind of callback
Our earlier callback-to-async article explains the basic bridge. Stack Overflow’s NSItemProvider question also already has an answer using a checked continuation. This post adds task cancellation and ownership of the returned Progress; it isn’t a newly discovered way to use await.
The broader ownership problem is well established. The leaked-continuation question has over 34,000 cumulative views and two answers as of October 26, 2026. Missing completion paths and overwriting another request’s waiter are still bugs with a newer continuation type.
Keep this adapter for an operation that produces one result. A delegate that legitimately reports repeated events needs a different model, such as an owned AsyncStream. Ignoring every event after the first isn’t a repair for an event stream.
Prefer a suitable native async API when one exists. Here we’re starting with an NSItemProvider, whose typed data-loading method takes a callback and returns Progress. PhotosPickerItem is a different type with different APIs; this example makes no claim to fix iCloud Photos loading.
Separate the three cancellation questions
Itsuki’s article about async functions that don’t cancel makes a useful distinction: allowing the caller to continue isn’t the same as stopping the underlying work. Nikolai Ruhe’s automatically cancelling continuations discussion explores the competing completion paths and lock boundary. We’ll apply those ideas to a concrete provider handle.
There are three separate results to account for:
| Question | What this adapter does |
|---|---|
| Can the task stop waiting for the callback? | Cancellation can take the continuation and resume it with CancellationError. |
| Does the provider receive a cancellation request? | Call Progress.cancel() if cancellation wins, including when the handle arrives later. |
| Has the provider actually stopped its work? | That depends on the producer. This adapter doesn’t certify it. |
Apple’s cancellation-handler contract says the operation still executes for an already-cancelled task. Cancellation can also run concurrently with the operation. A separate Task.isCancelled check followed by unsynchronized installation leaves a gap between those steps.
We need a small synchronized owner that exists before installing the handler. Its state moves from waiting to completed or cancelled, and never moves back.
| Ordering | Required result |
|---|---|
| Cancellation before continuation installation | Reject installation, resume with cancellation, and skip provider startup. |
| Cancellation after installation, before the handle returns | Release the waiter; cancel the handle when attached. |
| Completion before handle attachment | Keep the result; discard the unneeded cancellation action. |
| Completion racing cancellation | Accept one outcome; later attempts do nothing. |
“First” means the first transition to acquire the lock, not which event a wall clock would place first.
Give the continuation one owner
WWDC26’s Swift update introduces the new ownership tools. SE-0528 specifies Continuation: resuming consumes the value, so a direct second use is a compile-time error. Dropping an unresumed value traps. Retaining one forever can still leave its task suspended forever; there is no automatic timeout.
That makes ownership easier to audit, but doesn’t select a winner between a callback and cancellation. The mutex does that part. The installed SDK marks the new continuation API available from OS 27. For older deployment targets, keep a checked-continuation implementation with equivalent synchronization; a newer compiler doesn’t remove this runtime requirement.
Put these three Swift blocks together in one source file. State and Effects are ~Copyable because they can contain the noncopyable continuation. take() moves an optional’s contents out and leaves it empty.
The slot stores two different handles: a continuation that releases the waiting task, and a cancellation closure that asks the provider to stop. install supplies the first; attach supplies the second, possibly after cancellation has already won.
import Foundation
import Synchronization
import UniformTypeIdentifiers
nonisolated enum ProviderLoadError: Error, Equatable {
case missingData
case tooLarge
case invalidUTF8
}
// One instance per load. Install the continuation and attach the handle once.
@available(iOS 27.0, macOS 27.0, *)
nonisolated final class LoadSlot<Value: Sendable>: Sendable {
typealias Cancel = @Sendable () -> Void
enum Phase { case waiting, completed, cancelled }
struct State: ~Copyable {
var phase = Phase.waiting
var continuation: Continuation<Value, any Error>?
var cancelAction: Cancel?
var didAttach = false
}
private let state = Mutex(State())
func install(_ continuation: consuming Continuation<Value, any Error>) -> Bool {
var incoming: Continuation<Value, any Error>? = consume continuation
let accepted = state.withLock { state in
guard state.phase == .waiting else { return false }
precondition(state.continuation == nil)
state.continuation = incoming.take()
return true
}
if let rejected = incoming.take() {
rejected.resume(throwing: CancellationError())
}
return accepted
}
func attach(_ action: @escaping Cancel) {
let cancelNow = state.withLock { state in
precondition(!state.didAttach)
state.didAttach = true
switch state.phase {
case .waiting: state.cancelAction = action; return false
case .completed: return false
case .cancelled: return true
}
}
if cancelNow { action() }
}
func complete(_ result: Result<Value, any Error>) {
let effects = state.withLock { state -> Effects in
guard state.phase == .waiting else { return Effects() }
state.phase = .completed
return Effects(
continuation: state.continuation.take(),
action: state.cancelAction.take()
)
}
if let continuation = consume effects.continuation {
continuation.resume(with: result)
}
// Dropping a captured owner may run its deinit. Release it outside lock too.
withExtendedLifetime(effects.action) {}
}
struct Effects: ~Copyable {
var continuation: Continuation<Value, any Error>?
var action: Cancel?
}
func cancel() {
// A noncopyable aggregate moves both effects out before invoking either.
let effects = state.withLock { state -> Effects in
guard state.phase == .waiting else { return Effects() }
state.phase = .cancelled
let continuation = state.continuation.take()
let action = state.cancelAction.take()
return Effects(continuation: consume continuation, action: action)
}
if let continuation = consume effects.continuation {
continuation.resume(throwing: CancellationError())
}
effects.action?()
}
}
The lock protects only the state transition and transfer of ownership. resume, the cancellation action, and destruction of its captured objects happen after the lock is released. Apple specifically warns against resuming continuations while holding a lock acquired by a cancellation handler. A producer’s cancellation callback may also call back into our adapter; running it under the lock would invite a deadlock.
The withExtendedLifetime on the completed path is deliberate. Dropping the last reference held by the cancellation closure can run an object’s deinit. Moving the closure out, then keeping it alive until we’re outside the lock, keeps that hidden callback outside too.
This helper is private implementation machinery for one load: install once, attach once, and only complete after installation. Create a fresh instance per request. It is not a shared slot for all imports.
Connect the provider and its late handle
Now the framework bridge is small:
// Data loading necessarily materializes the provider's Data first. This limit
// rejects an oversized result; it does not bound the provider's allocations.
@available(iOS 27.0, macOS 27.0, *)
@MainActor func loadUTF8TextData(
from provider: NSItemProvider,
maximumBytes: Int = 1_048_576
) async throws -> Data {
precondition(maximumBytes >= 0)
let slot = LoadSlot<Data>()
return try await withTaskCancellationHandler {
try await withContinuation(of: Data.self, throwing: (any Error).self) { continuation in
guard slot.install(consume continuation) else { return }
let progress = provider.loadDataRepresentation(for: .utf8PlainText) { data, error in
if let error {
slot.complete(.failure(error))
} else if let data {
if data.count <= maximumBytes {
slot.complete(.success(data))
} else {
slot.complete(.failure(ProviderLoadError.tooLarge))
}
} else {
slot.complete(.failure(ProviderLoadError.missingData))
}
}
slot.attach { progress.cancel() }
}
} onCancel: { slot.cancel() }
}
The provider’s completion may arrive on an arbitrary queue. It touches the sendable slot, not view state. We start the provider on MainActor as an explicit ownership choice for a provider received by UI code; that doesn’t move its callback onto the main actor.
Requesting .utf8PlainText also gives the example a specific encoding contract. If your import accepts other types, choose their representation and decoding rules deliberately.
Two details matter here. First, forward the error delivered by the provider. Foundation may wrap a producer’s error; retaining the error object preserves its domain, code and underlying-error information. Second, maximumBytes rejects data after delivery. It is an acceptance limit, not a bound on the provider’s allocations. Large-file imports need a file-based design with proper temporary-file ownership.
Cancellation can happen just after install succeeds and before the provider starts. We cannot close that gap by running arbitrary provider code under the lock: it may complete synchronously. Instead, the waiter remains cancelled and the returned handle is cancelled when attached. This promise does not include preventing every cancelled operation from starting. Startup and cancellation callbacks must also return promptly; the wrapper cannot make a blocking synchronous call disappear.
Progress.cancel() marks cancellation and invokes its cancellation handler. It doesn’t provide proof that an external producer has finished tearing down.
Check again before accepting the import
A completion may win immediately before the task is cancelled. Returning that result is consistent with our adapter’s rule. The caller can apply a stricter rule before using it:
@available(iOS 27.0, macOS 27.0, *)
@MainActor func importUTF8Text(from provider: NSItemProvider) async throws -> String {
let data = try await loadUTF8TextData(from: provider)
// Completion may have won just before cancellation. Check before using it.
try Task.checkCancellation()
guard let text = String(data: data, encoding: .utf8) else {
throw ProviderLoadError.invalidUTF8
}
return text
}
A calling task can handle CancellationError as a normal cancelled import and report other errors separately. Keep the task handle if the UI has a Cancel button, and call cancel() on that handle. The final check prevents a cancellation already visible at that point from becoming an accepted import; it cannot make future cancellation and a later database write one atomic action.
This function decodes UTF-8, but it doesn’t validate an application’s document format. If the text is JSON, a command, or a template, validate that structure before changing app state.
Test the orderings, not a lucky delay
The download uses controllable producers and synchronization signals, not a sleep intended to make cancellation happen first. Its checks cover:
- An already-cancelled task that never starts the provider, plus cancellation before continuation installation.
- Cancellation before handle attachment, a synchronous completion before attachment, and repeated late completion attempts.
- Cancellation actions and captured-object destruction that reenter the slot.
- Real own-process
NSItemProvidersuccess, error-chain preservation, oversized data, invalid UTF-8, and cancellation reaching the producer’sProgresshandler. - Concurrent completion, cancellation and handle attachment from separate dispatch queues, with either valid terminal winner accepted.
The exact declarations and caller compile with warnings treated as errors in ordinary and default MainActor isolation. The checks run on macOS and in a native iOS 27 Simulator app; separate Thread Sanitizer runs exercise the concurrent host cases. A deliberate double-resume example is rejected by the compiler. These checks cover our own registered producer, not another app, a physical device, or Photos/iCloud behavior.
If neither a callback nor cancellation arrives, this operation can still wait indefinitely. Adding a deadline is a separate policy. The useful result here is narrower: one owner decides how the wait ends, and a late cancellation handle doesn’t get forgotten.