Akoz
Tech with Akoz

Tech with Akoz

How to detect a screenshot from Simulator

How to detect a screenshot from Simulator

Use LLDB to mimic the behavior.

Akoz's photo
Akoz

Published on Oct 17, 2021

1 min read

Last month on my project, I was working on a feature that involves detecting screenshots because it has sensitive data. At that time I didn't have a real iOS device and it got me a problem because only real devices can detect such behavior.

So here's how I did on a simulator to mimic taking screenshots.

1 - Let's create a simple view with Button as if it is a screenshot button.

import SwiftUI

struct ContentView: View {

    let pub = NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)

    var body: some View {
        VStack {
            Text("Hello, world!")
                .padding()
            Button(action: {
                print("Button tapped")
            } ) {
                Text("Screenshot")
                    .padding()
                    .foregroundColor(Color.white)
                    .background(Color.blue)
                    .cornerRadius(15)
            }
        }.onReceive(pub, perform: { _ in
            self.detectScreenshot()
        })
    }

    func detectScreenshot() {
        print("Screenshot is taken")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2- Let's put a breakpoint on the Button action, put the following command debug area and Press Enter.

(lldb) expr NotificationCenter.default.post(name: UIApplication.userDidTakeScreenshotNotification, object: nil)

ezgif.com-gif-maker (2).gif

That's about it. Easy right?
You can post other notifications as well using LLDB.

Reference: stackoverflow.com/questions/28209538/how-to..

 
Share this