如何使用 FileManager 进行类似 Finder 的特权操作?

How to perform privileged operation like Finder using FileManager?

启动后 Xcode I select File/New/Project/macOS/Command Line Tool/Next and 运行如下代码:

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 Code=513 "“MyApp” couldn’t be moved because you don’t have permission to access “Applications”." UserInfo={NSSourceFilePathErrorKey=/Applications/MyApp.app, NSUserStringVariant=( Move ), NSDestinationFilePath=/Applications/MyApp-Renamed.app, NSFilePath=/Applications/MyApp.app, NSUnderlyingError=0x100617380 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}

该应用未被沙盒化。如何解决这个问题?

如果我没理解错的话,获得授权不会提升你的流程。您只需获得一个授权参考来验证它或与另一个 API 一起使用,让您执行特权操作。比如启动特权进程或将其传递给特权帮助工具。

‪Authorization Services Tasks