..

实现 macOS 锁屏的两种方式

逛了一圈发现所有的远程锁定 App 都是基于蓝牙的,因此会有距离的问题=。=,并且蓝牙需要进行配对操作……于是自己写了个基于局域网 Socket 的远程锁定 LockMyMac ,再也不用担心想起忘记锁电脑却已走太远的情况了。

CGSession

大部分应用采用的方式,锁定时会有一个 3D 翻转的效果。

缺点:解锁只能使用密码登录,无法通过 Apple watch 自动登录

- (void)lockScreen {
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession"];
    [task setArguments:@[@"-suspend"]];
    [task launch];
}

Keychain

比较完美的一种锁屏方式,没有 3D 翻转效果,并可以通过 Apple watch 自动登录。

缺点:无法上架 Apple Store

- (void)lockScreen {
    NSBundle *bundle = [NSBundle bundleWithPath:@"/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu"];
    Class principalClass = [bundle principalClass];
    id instance = [[principalClass alloc] init];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    [instance performSelector:@selector(_lockScreenMenuHit:) withObject:nil];
#pragma clang diagnostic pop
}

其它方式

具体可以 Google 搜索,原理跟以上两种方式基本一致,不同的实现方式罢了~