macOS 开发 - 使用 LaunchAgents 实现开机自启动

开机自启动功能可以由多种方式实现,这里介绍使用 LaunchAgents 来实现。
方法就是,在 /Users/administrator/Library/LaunchAgents/ 目录下写入你的应用信息。


#pragma mark - 设置开机自启动
- (void)setLaunchAgents{

    NSString* launchFolder = [NSString stringWithFormat:@"%@/Library/LaunchAgents",NSHomeDirectory()];
    NSString * bundleID = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleIdentifierKey];

    NSString* dstLaunchPath = [launchFolder stringByAppendingFormat:@"/%@.plist",bundleID];

    NSLog(@"dstLaunchPath : %@",dstLaunchPath);
    //dstLaunchPath : /Users/administrator/Library/LaunchAgents/com.melissashu.www.MSLaunchAgentsLogin.plist

    NSFileManager* fm = [NSFileManager defaultManager];
    BOOL isDir = NO;
    //已经存在启动项中,就不必再创建
    if ([fm fileExistsAtPath:dstLaunchPath isDirectory:&isDir] && !isDir) {
        return;
    }
    //下面是一些配置
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    [arr addObject:[[NSBundle mainBundle] executablePath]];
    [arr addObject:@"-runMode"];
    [arr addObject:@"autoLaunched"];
    [dict setObject:[NSNumber numberWithBool:true] forKey:@"RunAtLoad"];
    [dict setObject:bundleID forKey:@"Label"];
    [dict setObject:arr forKey:@"ProgramArguments"];
    isDir = NO;
    if (![fm fileExistsAtPath:launchFolder isDirectory:&isDir] && isDir) {
        [fm createDirectoryAtPath:launchFolder withIntermediateDirectories:NO attributes:nil error:nil];
    }

    NSLog(@"dict : %@",dict);

    [dict writeToFile:dstLaunchPath atomically:NO];
}

如果想要设置为开机不自启动,将 RunAtLoad 这个key 设置为 false 即可。
[dict setObject:[NSNumber numberWithBool:true] forKey:@"RunAtLoad"];

你也可以到/Users/administrator/Library/LaunchAgents/ 目录下查看其它文件。

猜你喜欢

转载自blog.csdn.net/lovechris00/article/details/81483108