
Displaying an Alert When a Screenshot Is Taken in SwiftUI
This article was published more than one year ago. Please be aware that the information may be outdated.
This page has been translated by machine translation. View original
Users take screenshots in all sorts of situations, such as a weight graph in a weight management app, a workout list in a strength training app, or character stats in a game, and share them with friends or on social media. As app developers, there are quite a few scenes where we would like users to use a rich sharing feature (such as a feature for sharing richly decorated images) rather than a screenshot.
This article explains how to detect screenshot capture in an iOS app built with SwiftUI and display an alert to the user. You can use the screenshot notification as a trigger to convey a specific message to the user.
Displaying an Alert When a Screenshot Is Taken
As mentioned above, displaying a dialog to encourage social media sharing or providing guidelines when a screenshot is taken is an effective technique. For example, during a campaign, you could display an announcement dialog saying, "Share this screen on social media to get a special reward!"
It can also be used to raise awareness about copyright and privacy. On social media, there was talk about a manga app that shows a warning for up to three screenshots and locks the account on the fourth.
iOS posts the UIApplication.userDidTakeScreenshotNotification notification after a screenshot is taken. By using this, an app can take action in response to the capture. However, since this notification is received after the screenshot is taken, it cannot be used to prevent screenshots.
struct ContentView: View {
@State private var isPresented = false
var body: some View {
Text("Hello, world!")
.alert(isPresented: $isPresented) {
Alert(
title: Text("スクリーンショットが撮影されました"),
message: Text("この画面をSNSで共有しましょう!"),
dismissButton: .default(Text("OK"))
)
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in
isPresented = true
}
}
}
I actually ran the code above, took a screenshot, detected it, and displayed the alert.

Conclusion
Detecting screenshot capture and guiding users to a rich sharing feature can be a powerful tool for effectively communicating an app's features. On the other hand, showing alerts too frequently harms the user experience, so it may be hard to decide where to use this in real-world work. We should be careful to stay considerate of users.