How to use privacySensitive in swiftUI?

By | August 27, 2024

SwiftUI lets us mark some parts of our view as containing sensitive information, which in practice allows us to hide or show it more easily using redaction. To use this feature in your code, first add the privacySensitive() modifier to any views that should be hidden, then apply the .redacted(reason: .privacy) modifier at a higher place in your view hierarchy.

For example, this hides the user’s SSN number if the view is being displayed in a non-private context.

        VStack {
            Text("SSN number")
                .font(.headline)
            Text("33445 5678 3245 3456")
                .privacySensitive()
        }

By default, privacy sensitive context is masked out with a gray box, but you can also provide custom layout by reading the redaction reasons from the environment:

struct ContentView: View {
    
    @Environment(\.redactionReasons) var redactionReasons
    
    var body: some View {
        VStack {
            Text("SSN number")
                .font(.headline)
            if redactionReasons.contains(.privacy) {
                Text("[HIDDEN]")
            } else {
                Text("1234 5678 9012 3456")
            }
        }
    }
}

Sometimes the system will apply privacy redaction automatically, such as if your widget appears on the Lock Screen (when the user swipes to the left), or if they have their Apple Watch set to always-on and your app is visible – these are both good places where you should mark things as being privacy sensitive.

Leave a Reply

Your email address will not be published. Required fields are marked *