Mac开发-10.14获取文件操作权限-管理员权限获取

本文介绍了在MacOS 10.14上获取文件操作权限的方法,包括使用NSAppleScript执行脚本、利用Security框架进行权限获取,以及通过ServiceManagement注册LaunchdDaemon。在无法使用NSTask获取权限时,可以使用NSAppleScript并根据用户权限决定是否以管理员身份运行。同时,通过Security框架的函数来检查和获取必要的权限。另外,ServiceManagement提供的新方式能在不使整个应用运行在高权限下,仅针对特定任务赋予root权限。
摘要由CSDN通过智能技术生成


Mac os 10.14以及 Mac os 10.15之后,系统对部分文件夹下的操作权限判断更加严格,需要获得管理员权限,在输入命令行时,我们通常加上 sudo来进行获取权限,同时输入密码。在Mac os开发中,也面临这样的问题,就需要主动获取权限。
我的场景是做 MacOS的更新功能,需要替换 Application下的应用程序(先删除再移动新app到 Application目录)。在Mac os 10.14以上版本中,需要获得管理员权限。

使用NSAppleScript来操作

使用 NSTask 不能获取相关权限,所以使用NSAppleScript来进行权限获取的同时,执行脚本。

Boolean runProcessAsAdministrator( NSString *scriptPath, NSArray *arguments,BOOL isAdmin, NSString **output,NSString **errorDescription)
{
   
    NSString * allArgs = [arguments componentsJoinedByString:@" "];
    NSString *isAdminPre = @"";
    if (isAdmin) {
   
        isAdminPre = @"with administrator privileges";
    }
    NSString * fullScript = [NSString stringWithFormat:@"%@ %@", scriptPath, allArgs];
    NSDictionary *errorInfo = [NSDictionary new];
    NSString *script = [NSString stringWithFormat:@"do shell script \"%@\" %@", fullScript,isAdminPre];
    NSLog(@"script = %@",script);
    NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
    NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];
    // Check errorInfo/var/tmp
    if (! eventResult)
    {
   
        // Describe common errors
        *errorDescription = nil;
        if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
        {
   
            NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
            if ([errorNumber intValue] == -128)
                *errorDescription = @"The administrator password is required to do this.";
        }
        // Set error message from provided message
        if (*errorDescription == nil)
        {
   
            if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
                *errorDescription = (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
        }
        return NO;
    }
    else
    {
   
        // Set output to the AppleScript's output
        *output = [eventResult stringValue];
        return YES;
    }
}

runProcessAsAdministrator(脚本路径,参数数组,是否管理员权限运行,输出结果,错误描述)

使用方法

    NSString *output = nil;
    NSString *errorDescription = nil;
    runProcessAsAdministrator(@
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值