NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to mark content as private using privacySensitive()

Paul Hudson    @twostraws   

Updated for Xcode 14.2

New in iOS 15

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 credit card number if the view is being displayed in a non-private context:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Card number")
                .font(.headline)

            Text("1234 5678 9012 3456")
                .privacySensitive()
        }
    }
}

Download this as an Xcode project

The text “Card Number” over a long string of digits.

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("Card number")
                .font(.headline)

            if redactionReasons.contains(.privacy) {
                Text("[HIDDEN]")
            } else {
                Text("1234 5678 9012 3456")
            }
        }
    }
}

Download this as an Xcode project

The text “Card Number” over the placeholder text “[HIDDEN]”.

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.

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.