skip to content

With FileManager on iOS, why does a scanning app's background task fail to read its scan index while the phone is locked, though the same read works with the app open?

level: seniorimportance: should knowfreq 30%

answer

  1. encryption keys and the lock screen
  2. a file attribute, not a folder rule
  3. classes dating from iOS 4 and 5
  4. first unlock after boot
  5. a writing option chosen per file

basics

~20 s

The index was written with FileProtectionType.complete, which makes a file unreadable while the device is locked. Files that locked-phone background work needs should use completeUntilFirstUserAuthentication, readable after the first unlock since boot, while user documents can stay complete.

solid answer

~40 s

iOS encrypts each file with a key tied to its data-protection class, and the class decides when the key is available. The index was written with `.completeFileProtection`, so its class is `FileProtectionType.complete`: the documentation says such a file cannot be read or written while the device is locked or booting, so a background launch on a locked phone gets a thrown error while the open app, on an unlocked phone, reads it fine. The fix is to give files that background work needs `completeUntilFirstUserAuthentication`, readable once the user has unlocked since boot even if the phone is locked again, and keep the PDFs themselves at `complete`. I set the class when writing with a `Data.WritingOptions` protection option, or later with `setAttributes([.protectionKey: ...], ofItemAtPath:)`, and I test on a locked device.

code

swift · 17 lines
swift
import Foundation
import UIKit

func writeScanIndex(_ data: Data, to url: URL) throws {
    // readable by a background launch once the user has unlocked since boot
    try data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
}

func setProtection(_ type: FileProtectionType, on url: URL) throws {
    try FileManager.default.setAttributes([.protectionKey: type],
                                          ofItemAtPath: url.path(percentEncoded: false))
}

@MainActor
func completeFilesReadableNow() -> Bool {
    UIApplication.shared.isProtectedDataAvailable
}

go deeper

for a junior

Recall that iOS files carry a protection class and that complete files cannot be read while the phone is locked.

for a middle

Explain the main classes, which Data.WritingOptions value sets each one at write time, and how setAttributes with protectionKey changes an existing file.

for a senior

Diagnose the locked-phone background failure from the file's actual class, pick the class per file, and handle the before-first-unlock window instead of crashing or retrying blindly.

for a principal

Weigh a strict app-wide default class against the background features it breaks, and own the short list of files that are deliberately lowered and why.

## What a protection class is On iOS every file carries a **data-protection class**, stored as the file attribute `FileAttributeKey.protectionKey` with a `FileProtectionType` value. The class decides **when the system makes the file's encryption key available**, and so when the app can read or write the file. It is independent of whether the file is backed up. | `FileProtectionType` | Readable and writable | Typical use | |---|---|---| | `.complete` | only while the device is unlocked; not while locked or booting | the user's scans and other sensitive documents | | `.completeUnlessOpen` | new files can be created while locked; once closed, not reopened until unlock; a handle opened while unlocked keeps working | a file written in the background, such as a download arriving while locked | | `.completeUntilFirstUserAuthentication` | after the first unlock since boot, even when locked again | indexes, databases and models that background work reads | | `.none` | at any time | data with no confidentiality need that must be read even before the first unlock | `complete` and `none` date from iOS 4, `completeUnlessOpen` and `completeUntilFirstUserAuthentication` from iOS 5. iOS 17 added `completeWhenUserInactive`: after the first unlock the file stays readable while the device is locked only until an access expiry, renewed when the user unlocks again. ## Why the read fails only in the background When the user has the app open, the phone is unlocked and every class is readable. A background task, a background download finishing, or a silent notification can wake the app **while the phone is locked**. With the index written as `.complete`, the key is unavailable at that moment and the read throws. Nothing is wrong with the path, the data or the code; the class is wrong for the job. The same class can be set by accident. A team may choose a stricter default class for the whole app through the Data Protection capability, and then new files the app creates get that class unless the code picks another, including the ones background work needs. ## Fixing it 1. **Find the file's actual class.** `try url.resourceValues(forKeys: [.fileProtectionKey]).fileProtection` returns it as a `URLFileProtection`; `attributesOfItem(atPath:)` shows it under `.protectionKey`. 2. **Write background-read files with the right option.** `data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])`. The other options are `.noFileProtection`, `.completeFileProtection`, `.completeFileProtectionUnlessOpen` and, from iOS 17, `.completeFileProtectionWhenUserInactive`. 3. **Change an existing file** with `FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath:)`. In Swift, `URLResourceValues.fileProtection` is get-only, so `setResourceValues(_:)` cannot change it. 4. **Handle the window before the first unlock.** Even `completeUntilFirstUserAuthentication` files are locked after a reboot until the user unlocks once, so catch the error and retry later instead of treating it as corruption. UIKit's `UIApplication.shared.isProtectedDataAvailable` and `UIApplication.protectedDataDidBecomeAvailableNotification` tell the app whether protected files are available now and when they become available, usually at unlock. ## Choosing per file - **Keep the scans at `complete`.** Only the open app, on an unlocked phone, needs them. - **Lower only what background work reads.** The index and the downloaded model can use `completeUntilFirstUserAuthentication`. - **Use `completeUnlessOpen` for files created while locked** that must not be readable again until unlock. - **Avoid `none`** unless the data must be read before the first unlock and holds nothing sensitive. Scheduling the background task itself belongs with the Background Tasks framework, and keychain items have their own accessibility classes with the same lock-state idea; deciding which secrets to keep on the device at all is security design, covered with secrets on device. ## Testing it A debug session on an unlocked phone never shows the bug, because every class is readable while the device is unlocked. A useful routine: 1. Log each file's class at launch with `resourceValues(forKeys: [.fileProtectionKey])`, so a bug report shows what the code actually wrote. 2. Lock the device, trigger the background work, and read the console for the thrown read error. 3. Reboot, do not unlock, trigger the work again, and confirm the code defers instead of treating the file as corrupt. The documentation also notes that `completeUnlessOpen` carries a small performance cost when a file is created and opened, though not while it is read or written, which is one more reason to reserve it for the files that need it.

  • A background download of a scan finishes while the phone is locked. Which class lets the app save it there but not reread it until unlock?
    `completeUnlessOpen`. The documentation says files with this class can be created while the device is locked, but once closed they cannot be opened again until the device is unlocked, and a file opened while unlocked stays usable after the user locks. It suits writing incoming data in the background while keeping it unreadable at rest on a locked phone.
  • Why not simply mark every file as FileProtectionType.none to avoid these failures?
    Because `none` drops the protection entirely: the file can be read at any time, including before the first unlock after boot. The failures come from mismatched classes, not from protection itself. Lowering only the files background work reads, to `completeUntilFirstUserAuthentication`, fixes the bug and keeps the user's scans at `complete`.

  • Marking every file complete because it is the most secure class
  • Believing completeUntilFirstUserAuthentication files are readable right after a reboot
  • Setting every file to none to stop background read failures
  • Expecting URLResourceValues.fileProtection to be settable through setResourceValues
  • Testing background file reads only while the phone is unlocked