Many operations under MacOS require administrator privileges, such as when we run chmod and can use sudo chmod at the command line to request to run with administrator privileges. However, programs written with Xcode cannot be used with sudo.
You need to write your own code to request permission. The following is an example of running chmod 777 as an administrator
bool ChmodFileWithElevatedPrivilegesFromLocation(NSString *location)
{
// Create authorization reference
OSStatus status;
AuthorizationRef authorizationRef;
status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);
if (status != errAuthorizationSuccess)
{
NSLog(@"Error Creating Initial Authorization: %d", status);
return NO;
}
AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};
AuthorizationRights rights = {1, &right};
AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;
status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);
if (status != errAuthorizationSuccess)
{
NSLog(@"Copy Rights Unsuccessful: %d", status);
return NO;
}
// use chmod
char *tool = "/bin/chmod";
char *args[] = {"777", (char *)[location UTF8String], NULL};
FILE *pipe = NULL;
status = AuthorizationExecuteWithPrivileges(authorizationRef, tool, kAuthorizationFlagDefaults, args, &pipe);
if (status != errAuthorizationSuccess)
{
NSLog(@"Error: %d", status);
return NO;
}
status = AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
return YES;
}
Calling methods
bool bRet = ChmodFileWithElevatedPrivilegesFromLocation("/Library");
if(bRet)
{
NSLog(@"error");
}
else
{
NSLog(@"sucess");
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Objective-c MacOS running programs with Administrator privileges