LoginSignup
1
1

More than 3 years have passed since last update.

Swift:画面収録の許可が必要なアプリで許可の状態を確認してダメなら許可を促す

Posted at

はじめに

macOS Catalinaから、アクセシビリティに関するセキュリティが向上し、画面をキャプチャするようなアプリ(画面共有やカラーピッカーなど)では画面収録の許可が必要になりました。しかし、許可に慣れていないユーザは初回起動時に出てきたポップアップに驚いて許可をしてくれない可能性があります。しかし、この許可のポップアップはデフォルトでは最初の一回目しか表示されないため、ユーザに許可を促す導線が必要となります。ここで、許可の状態を取得して、必要に応じて環境設定の画面収録許可のページを表示する機能が欲しくなります。

許可の状態を確認して、許可されていない時に許可を促す

func checkPermission() {
    if let _ = CGDisplayStream(display: CGMainDisplayID(),
                               outputWidth: 1,
                               outputHeight: 1,
                               pixelFormat: Int32(kCVPixelFormatType_32BGRA),
                               properties: nil,
                               handler: { _, _, _, _ in }) {
        print("has a permission")
        return
    }
    print("does not have a permission")

    let userInfo: [String: Any] = [
        NSLocalizedDescriptionKey: "This application does not have the screen capture permission.",
        NSLocalizedRecoverySuggestionErrorKey: "Please grant access to this application in Security & Privacy preferences, located in System Preferences."
    ]

    let error = NSError(domain: "ApplicationDomain", code: 0, userInfo: userInfo)
    let alert = NSAlert(error: error)
    alert.addButton(withTitle: "Deny")
    alert.addButton(withTitle: "Open System Preferences")
    let result = alert.runModal()

    if result == .alertSecondButtonReturn {
        let path = "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
        NSWorkspace.shared.open(URL(string: path)!)
    }
}

viewDidLoad() { // どこか初期化のタイミングで
    if #available(macOS 10.15, *) {
        checkPermission()
    }
}

これが必要となるのはCatalina以降なので、Mojave以前をサポートしている場合はOSのバージョンで場合分けするのを忘れずに。

参考文献

1
1
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
1
1