Skip to main content

How to encrypt SwiftData

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

How to encrypt SwiftData 관련

SwiftData by Example

Back to Home

How to encrypt SwiftData | SwiftData by Example

How to encrypt SwiftData

Updated for Xcode 15

If you’re storing information that’s particularly sensitive, you can take one or perhaps two steps to make sure it’s stored extra carefully.

The simplest, guaranteed to work option is to use the .allowsCloudEncryption attribute on any property that should be stored encrypted in iCloud, like this:

@Attribute(.allowsCloudEncryption) var cardNumber: Int

As the name suggests, this encryption only works in iCloud; this property has no effect on locally stored data.

The second, much more complex option is to attempt to set custom data protection properties in your data. Apple’s documentation here is rather thin on the ground, and cunning it’s impossible to verify that any of these actually work because the process of unlocking your phone also decrypts the data, however in theory you’d need to write code like this:

if let path = modelContext.container.configurations.first?.url.path(percentEncoded: false) {
    let attrs = [FileAttributeKey.protectionKey: FileProtectionType.completeUnlessOpen]
    try? FileManager.default.setAttributes(attrs, ofItemAtPath: path)
}

You may also need to enable the Data Protection capability for your app in Xcode.

However, this approach is more complicated than it might appear:

  1. The underlying data store is likely to be split into multiple files in order to support write-ahead logging, and they shouldn’t necessarily have the same protection class.
  2. SQLite can delete and recreate files at will as part of its self-healing mechanisms.
  3. If you’re supporting Core Data at the same time, you should adjust the NSPersistentStoreFileProtectionKey option key to match whatever you enabled for SwiftData.

Remember, it’s hard to verify that your files are encrypted because the very act of trusting your Mac to read the files makes them available unencrypted. So, I’d advise treading carefully!


이찬희 (MarkiiimarK)
Never Stop Learning.