文章目录
  1. 1. 注册开机启动
  2. 2. 取消开机启动
  3. 3. 索引

本文目的是将你的程序添加为开机启动,效果如下图

@添加为登录项中

具体实现如下

虽然API提醒为过期,但是在WWDC中提到过依旧可以使用,具体出处忘记了,值得注意的是这种方式好像是不可以上架App Store的,具体原因见Designing for App Sandbox->Creating a Login Item for Your App

注册开机启动

1
2
3
4
5
6
7
8
9
10

+(void)LoginItem{
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
//url为app所在的目录
NSString * appPath = [NSBundle mainBundle].bundlePath;
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:appPath];
LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemLast, NULL, NULL, url, NULL, NULL);
CFRelease(item);
CFRelease(loginItems);
}

取消开机启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

+(void)cancleLoginItem{
UInt32 seedValue;
CFURLRef thePath;
NSString * appPath = [NSBundle mainBundle].bundlePath;
LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
CFArrayRef loginItemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
for (id item in (__bridge NSArray *)loginItemsArray) {
LSSharedFileListItemRef itemRef = (__bridge LSSharedFileListItemRef)item;
if (LSSharedFileListItemResolve(itemRef, 0, (CFURLRef*) &thePath, NULL) == noErr) {
//appPath目录为要取消开机启动app的路径
if ([[(__bridge NSURL *)thePath path] hasPrefix:appPath]) {
LSSharedFileListItemRemove(loginItems, itemRef); // Deleting the item
}
CFRelease(thePath);
}
}
CFRelease(loginItemsArray);
CFRelease(loginItems);
}

索引

plapier/LaunchStarter.swift
File System Programming Guide(iOS)
Mac OSX的开机启动配置
注册程序为开机自启动
App Sandbox Design Guide
file_system_programming_guide

文章目录
  1. 1. 注册开机启动
  2. 2. 取消开机启动
  3. 3. 索引