2

启动 Xcode 后,我选择File / New / Project / macOS / Command Line Tool / Next并运行以下代码:

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)
}

不幸的是,这个程序不起作用:

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

该应用程序不是沙盒化的。如何解决问题?

4

1 回答 1

2

如果我理解正确,获得授权不会提升您的流程。您只需获得一个授权参考来验证它或与另一个 API 一起使用,从而让您执行特权操作。就像启动特权进程或将其传递给特权帮助工具一样。</p>

授权服务任务

于 2020-01-16T20:02:08.257 回答