LoginSignup
125
109

More than 5 years have passed since last update.

【Swift4】iOSでユーザーがスクリーンショットを撮ったら何かする【小ネタ】

Last updated at Posted at 2016-05-30

こんなのあるんだというのを最近知ったので、小ネタとして残します。

  • 2016/10/19 追記:Swift3でのコードを追加しました。
  • 2017/10/01 追記:Swift4の記述を追加しました。

ユーザーがスクリーンショットを撮ったことを検知する

Swift3, Swift4

Swift3, Swift4 では、NSNotificationName構造体にstaticなプロパティとして以下が定義されています。

static let UIApplicationUserDidTakeScreenshot: NSNotification.Name

こちらをnotificationNameとしてNotificationCenterのobserverを仕込むことで、
「ホームボタン+電源ボタンの同時押し」によるスクリーンショットを撮ったことを検知することができます。

import UIKit

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Observerとして登録
        NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.userDidTakeScreenshot(_:)), name: .UIApplicationUserDidTakeScreenshot, object: nil)
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    // UIApplicationUserDidTakeScreenshot の通知を受けて実行される
    func userDidTakeScreenshot(notification: Notification) {
        // 何かする
    }

}

リファレンスにも書いていますが、通知を受けた際のNotificationのuserInfoには特に何も設定されていないので、上記の例でuserDidTakeScreenshotメソッド内でnotification.userInfoとしてもnilが返ってきます。

Swift2

let UIApplicationUserDidTakeScreenshotNotification: String

Swift2では上記のようなString型の定数が定義されています。

import UIKit

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Observerとして登録
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyViewController.userDidTakeScreenshot(_:)), name: UIApplicationUserDidTakeScreenshotNotification, object: nil)
    }

    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    // UIApplicationUserDidTakeScreenshotNotification の通知を受けて実行される
    func userDidTakeScreenshot(notification: NSNotification) {
        // 何かする
    }

}

応用

この通知を利用して、
スクリーンショットを撮った後にアラートを出したり、ユーザーが撮ったスクリーンショットを取得して、加工したものを新たに保存させるといったことができそうです。

参考:
http://www.toyship.org/archives/1633

また、アプリの内容によってはユーザーがどのくらいスクリーンショットを撮っているかというログを取るのもいいかもしれません。

注意点

  • 通知を受けるのはあくまでスクリーンショットを撮った ""
  • 通知にuserInfoが付与されていないので、「スクリーンショットを撮った」ということ以外に情報はない
  • 通知を受けた直後にはスクリーンショットの画像はまだカメラロールに保存されていない
    • →保存された画像を得るには処理を遅延させるなどの工夫が必要そう
  • iOS 7.0 以降で使用可

終わり

以上、使いどころは限られますが、そもそもスクショの検出はできないと思っていたので参考程度に書きました。

知らないことがまだまだたくさんあって面白いですね :laughing:

125
109
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
125
109