我根据你的问题做了研究,并找到了这个答案,如果你运行应用程序,它将显示应用程序无障碍并找到了这个解决方案,并且这个解决方案没有崩溃。不幸的是,原始方法(我留在这篇文章的底部)仍然提示应用程序的每个新版本的可访问性。
我必须在我的 macOS 应用程序中实现此功能,并且有另一种想法和方法来实现它,考虑到用户无论如何都需要执行它,我只需让应用程序在每次运行时显示所需的对话,并且在应用程序构建期间,我运行脚本清除现有权限。 (github 链接 ->https://github.com/othyn/macos-auto-clicker#gear-preferences-storage https://github.com/othyn/macos-auto-clicker#gear-preferences-storage)运行这个应用程序并进行相应的检查。
//
// PermissionsService.swift
// auto-clicker
//
// Created by Ben on 10/04/2022.
//
import Cocoa
final class PermissionsService: ObservableObject {
// Store the active trust state of the app.
@Published var isTrusted: Bool = AXIsProcessTrusted()
// Poll the accessibility state every 1 second to check
// and update the trust status.
func pollAccessibilityPrivileges() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.isTrusted = AXIsProcessTrusted()
if !self.isTrusted {
self.pollAccessibilityPrivileges()
}
}
}
// Request accessibility permissions, this should prompt
// macOS to open and present the required dialogue open
// to the correct page for the user to just hit the add
// button.
static func acquireAccessibilityPrivileges() {
let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true]
let enabled = AXIsProcessTrustedWithOptions(options)
}
}
在应用程序委托中添加此代码
//
// AppDelegate.swift
// auto-clicker
//
// Created by Ben on 30/03/2022.
//
import Foundation
import Cocoa
final class AppDelegate: NSObject, NSApplicationDelegate {
// When the application finishes launching, request the
// accessibility permissions from the service class we
// made earlier.
func applicationDidFinishLaunching(_ notification: Notification) {
PermissionsService.acquireAccessibilityPrivileges()
}
}
在您的视图中实现此代码,以向用户获取我们正在等待权限的反馈并侦听 isTrusted 更新值
//
// AutoClickerApp.swift
// auto-clicker
//
// Created by Ben on 12/05/2021.
//
import Foundation
import SwiftUI
import Defaults
@main
struct AutoClickerApp: App {
// Create an instance of the permissions service class that we
// can observe for the trusted state change.
@StateObject private var permissionsService = PermissionsService()
var body: some Scene {
// Wait for trust permissions being granted from the user,
// displaying a blocking permissions view telling the user
// what to do and then presenting the main application view
// automatically when the required trust permissions are granted.
WindowGroup {
if self.permissionsService.isTrusted {
MainView()
} else {
PermissionsView()
}
.onAppear(perform: self.permissionsService.pollAccessibilityPrivileges)
}
}
}
添加了图像以供参考。我希望它能解决你的问题。
然后,为了在应用程序构建期间自动清除权限,我向项目添加了一个新的构建脚本,该脚本针对 /bin/sh 运行以下命令:
tccutil reset Accessibility $PRODUCT_BUNDLE_IDENTIFIER
如 auto-clicker.xcodeproj/project.pbxproj(第 435 行)所示。
检查此链接->macOS 和 XCode 中开发的辅助权限 https://stackoverflow.com/questions/52214771/accessibility-permissions-for-development-in-macos-and-xcode
更新:修复您的代码问题,请查找附件图像以供参考。