//xcode9需要额外import这个,不然SCDynamicStoreCopyConsoleUser这个方法找不到
#import <SystemConfiguration/SystemConfiguration.h>
- (NSString *)getCurrentUserName
{
uid_t uid = 0;
gid_t gid = 0;
CFStringRef cfsUsrName = SCDynamicStoreCopyConsoleUser(NULL, &uid, &gid);
if (cfsUsrName == NULL) {
return @"";
}
NSString *userName = [NSString stringWithString:(__bridge NSString *)cfsUsrName];
CFRelease(cfsUsrName);
return userName;
}
- (BOOL)exec {
//获取用户名
NSString *userName = [self getCurrentUserName];
if (!userName || userName.length == 0) {
return NO;
}
NSString *str = @"defaults -currentHost write com.apple.screensaver idleTime 600";//这个是一个改屏保时间的命令
NSString *command = [NSString stringWithFormat:@"su - %@ -c \"%@\"", userName, str];
NSArray *arguments = [NSArray arrayWithObjects:@"-c", command, nil];
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:arguments];
[task launch];
[task waitUntilExit];//有了这行,就变成了同步的,没有就是异步的
int st = [task terminationStatus];
if (st == 0) {
return YES;
} else {
return NO;
}
}
网友评论