据我所知,这段代码应该使用提升权限运行我的脚本,但NSTask似乎并没有实际启动。我对Objective-C和Cocoa相对较新,所以我可能在这里遗漏了一些简单的东西,但无论如何我都不知道为什么这样做不起作用。
CFErrorRef error;
AuthorizationItem authItem = { kSMRightBlessPrivilegedHelper, 0, NULL, 0 };
AuthorizationRights authRights = { 1, &authItem };
AuthorizationFlags flags = kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;
AuthorizationRef auth;
if(AuthorizationCreate(&authRights, kAuthorizationEmptyEnvironment, flags, &auth) == errAuthorizationSuccess)
{
NSString* myLabel = @"com.hidden.backup";
(void) SMJobRemove( kSMDomainSystemLaunchd, (__bridge CFStringRef)myLabel, auth, false, NULL );
NSString *path = [[NSBundle mainBundle] pathForResource:@"kandorBackup" ofType:@"sh"];
NSPipe *outputPipe = [NSPipe pipe];
readHandle = [outputPipe fileHandleForReading];
inData = nil;
returnValue = nil;
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:path];
[task setArguments:[NSArray arrayWithObjects:login, selectedDrive, rsyncFinalFlags, nil]];
[task setStandardOutput:outputPipe];
[readHandle waitForDataInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(recievedData:)
name:NSFileHandleDataAvailableNotification
object:nil];
SMJobSubmit( kSMDomainSystemLaunchd, (__bridge CFDictionaryRef)task, auth, &error);
}
如果有帮助,我在Xcode调试区域中收到这两个错误:
2014-08-04 11:44:39.169 <hidden>[68065:303] -[NSConcreteTask objectForKey:]: unrecognized selector sent to instance 0x600000099d70
2014-08-04 11:44:39.169 <hidden>[68065:303] Exception detected while handling key input.
答案 0 :(得分:1)
SMJobSubmit不是用于提升NSTask。您宁愿以与LaunchDaemon / LaunchAgent plist文件相同的格式构造NSDictionary,并将该NSDictionary传递给SMJobSubmit。
你会这样做NSDictionary *dictionary = @{@"ProgramArguments": @[path,login, selectedDrive, rsyncFinalFlags]};
SMJobSubmit( kSMDomainSystemLaunchd, (__bridge CFDictionaryRef)dictionary, auth, &error);
不幸的是,你不会得到任何进展消息,如果你需要建立一个特权助手工具并从那里执行NSTask。