gpt4 book ai didi

macos - Swift 中的授权创建 (Xcode 6)

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:19 24 4
gpt4 key购买 nike

我一直在寻找一些帮助来为我的应用程序创建授权,让它以 root 身份运行一些 shell 脚本。我查看了 Apple 文档(当然是用 OBJ-C 编写的并且非常模糊),我正在尝试使用 Swift 中的代码示例。

AuthorizationCreate 函数立即出现错误:

    var authRef: AuthorizationRef
let osStatus = AuthorizationCreate(nil, nil, kAuthorizationFlagDefaults, &authRef)

“Int”不能转换为“AuthorizationFlags”

我只是想按照以下文档中的代码片段进行操作:https://developer.apple.com/library/mac/documentation/Security/Conceptual/authorization_concepts/03authtasks/authtasks.html#//apple_ref/doc/uid/TP30000995-CH206-TP9

我从这里找到了 kAuthorizationFlagDefaults 的常量:https://developer.apple.com/library/mac/documentation/Security/Reference/authorization_ref/#//apple_ref/doc/constant_group/Authorization_Options

如果重要的话,我在 10.10.1 中运行。

我已经看到使用 AppleScript 的解决方案,但我真的想避免这种情况。

最佳答案

kAuthorizationFlagDefaults 是一个 Int 并且必须转换为AuthorizationFlags(UInt32 的类型别名)。还必须初始化 authRef:

var authRef: AuthorizationRef = nil
let authFlags = AuthorizationFlags(kAuthorizationFlagDefaults)
let osStatus = AuthorizationCreate(nil, nil, authFlags, &authRef)

扩展示例(未经测试!):

var myItems = [
AuthorizationItem(name: "com.myOrganization.myProduct.myRight1",
valueLength: 0, value: nil, flags: 0),
AuthorizationItem(name: "com.myOrganization.myProduct.myRight2",
valueLength: 0, value: nil, flags: 0)
]

var myRights = AuthorizationRights(count: UInt32(myItems.count), items: &myItems)

let myFlags = AuthorizationFlags(kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagExtendRights)


var authRef: AuthorizationRef = nil
let authFlags = AuthorizationFlags(kAuthorizationFlagDefaults)
let osStatus = AuthorizationCreate(&myRights, nil, authFlags, &authRef)

编辑:Swift 3

var myItems = [
AuthorizationItem(name: "com.myOrganization.myProduct.myRight1",
valueLength: 0, value: nil, flags: 0),
AuthorizationItem(name: "com.myOrganization.myProduct.myRight2",
valueLength: 0, value: nil, flags: 0)
]

var myRights = AuthorizationRights(count: UInt32(myItems.count), items: &myItems)

let myFlags : AuthorizationFlags = [.interactionAllowed, .extendRights]


var authRef: AuthorizationRef?
let osStatus = AuthorizationCreate(&myRights, nil, myFlags, &authRef)

关于macos - Swift 中的授权创建 (Xcode 6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27423933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com