如何使用FileManager执行诸如Finder之类的特权操作?

问题描述 投票:1回答:1

启动Xcode后,我选择文件/新建/项目/ macOS /命令行工具/下一步并运行以下代码:

import SecurityFoundation

do {
  // Authorize for privileged operations
  guard
    let authorization = SFAuthorization.authorization() as? SFAuthorization,
    let right = NSString(string: kAuthorizationRuleAuthenticateAsAdmin).utf8String
  else {
    throw CocoaError(.fileWriteNoPermission)
  }
  try authorization.obtain(withRight: right, flags: [.extendRights, .interactionAllowed])
  defer { authorization.invalidateCredentials() }

  // Rename MyApp.app into MyApp-Renamed.app
  let sourceFileURL = URL(fileURLWithPath: "/Applications/MyApp.app")
  let destFileURL = sourceFileURL.deletingLastPathComponent().appendingPathComponent("MyApp-Renamed.app")
  try FileManager.default.moveItem(at: sourceFileURL, to: destFileURL)

} catch {
  print(error)
}

不幸的是,该程序无法运行:

Error Domain = NSCocoaErrorDomain代码= 513““ MyApp”无法移动因为您没有访问“应用程序”的权限。”UserInfo = {NSSourceFilePathErrorKey = / Applications / MyApp.app,NSUserStringVariant =(移动),NSDestinationFilePath = / Applications / MyApp-Renamed.app,NSFilePath = / Applications / MyApp.app,NSUnderlyingError = 0x100617380{Error Domain = NSPOSIXErrorDomain代码= 13“权限被拒绝”}}

该应用未沙盒化。如何解决此问题?

swift security nsfilemanager appkit authorizationservices
1个回答
0
投票

‪如果我理解正确,获得授权不会提升您的流程。您仅获得授权参考以进行验证或与其他API结合使用,从而可以执行特权操作。例如启动特权进程或将其传递给特权助手工具。‬

‪Authorization Services Tasks

© www.soinside.com 2019 - 2024. All rights reserved.