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(@