How do I protect sensitive files with file protection attributes in Swift?

In Swift, you can protect sensitive files by utilizing file protection attributes that are part of the iOS File Protection feature. This feature ensures that files are only accessible when the device is unlocked, adding an extra layer of security for user data.

Here's how to implement file protection attributes in Swift:

let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("sensitiveFile.txt") if let fileURL = fileURL { // Write data to the file let data = "This is sensitive data.".data(using: .utf8) do { try data?.write(to: fileURL, options: [.completeFileProtection]) print("File saved with complete file protection.") } catch { print("Error saving file: \(error)") } // To read the file when the device is unlocked do { let storedData = try Data(contentsOf: fileURL) let content = String(data: storedData, encoding: .utf8) print("File content: \(content ?? "")") } catch { print("Error reading file: \(error)") } }

Swift File Protection sensitive files iOS data security