在 MAC 应用程序中使用 NSTask 移除 Helper Tool

Remove Helper Tool using NSTask in MAC Application

我正在开发 mac 应用程序,我在其中使用 root 权限做一些事情并且工作正常,现在我想删除该帮助工具,所以我尝试使用删除该帮助工具下面的 NSTask 是代码。

NSTask *task = [[NSTask alloc] init];
NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Uninstall" ofType:@"sh"];
[task setLaunchPath:bundlePath];
[task setArguments:[NSArray arrayWithObjects:@"Uninstall.sh", nil]];
[task setStandardOutput:[NSPipe pipe]];
[task setStandardInput:[NSPipe pipe]];
[task launch];

它会提示用户密码,但随后提示权限被拒绝。

下面是我使用管理员权限从 mac 中删除辅助工具的代码。

在 fullScript 中编写您的终端命令并尝试。

-(void)removeHelperToolFromMac{

NSString * fullScript = @"write you terminal code here";

NSDictionary *errorInfo = [NSDictionary new];
NSString *script =  [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];

NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];

// Check errorInfo
if (!eventResult)
{
    // Describe common errors
    NSString *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];
    }
}
else
{ 
    // Set output to the AppleScript's output
    // Successfully delete files
}
}

希望对您有所帮助。