Mac开发-app开机启动

作者: Ryan___ | 来源:发表于2017-07-07 22:09 被阅读139次
    1. 新建工程,起名字为:mainProject
    2. 在新建的工程里,创建target,起名字为:launchHelper
    3. 配置launchHelper
      1. 删除launchHelper中的windows与Menu,让它没有可展示的Window。(注意不能将storyboard全部删除,只删除window及viewcontroller,menu必须留着)
    4. 设置launchHelper的Info中Application is background only为YES
    5. 设置launchHelper中Build Setting下skip install为YES
    6. 配置mainProject
    7. 在主APP Target(mainProject)在build phases中,点击左上角


      将launchHelper打包进主target
    8. 在主APP Target(mainProject)中添加CopyFile到Contents/Library/LoginItems
    9. 分别开启mainProject和launchHelper的App Sandbox
    10. 添加启动代码
    11. 在mainProject中你要设置开机启动的地方调用下面的代码
    -(void)autoLaunch:(BOOL)launch{
        NSString *helpApp = @"com.kingsoft.LaunchHelper";
        NSString *helperPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Contents/Library/LoginItems/LaunchHelper.app"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:helperPath]) {
            return;
        }
        NSURL *helperUrl = [NSURL fileURLWithPath:helperPath];
        // Registering helper app
        if (LSRegisterURL((__bridge CFURLRef)helperUrl, true) != noErr) {
            NSLog(@"LSRegisterURL failed!");
        }
        // com.xxx.xxx为Helper的BundleID,ture/false设置开启还是关闭
        if (!SMLoginItemSetEnabled((__bridge CFStringRef)helpApp,launch)) {
            NSLog(@"SMLoginItemSetEnabled failed!");
        }
    }
    
    1. 在launchHelper中Appdelegate中
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        NSString *mainAPP = @"com.kingsoft.powerWordForMac";
        NSString *appPath = [[NSBundle mainBundle] bundlePath];
        appPath = [appPath stringByReplacingOccurrencesOfString:@"/Contents/Library/LoginItems/LaunchHelper.app" withString:@""];
        //appPath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/PowerWordForMac"];
        appPath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/金山词霸"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:appPath]) {
            return;
        }
        NSArray *runningArray = [NSRunningApplication runningApplicationsWithBundleIdentifier:mainAPP];
        if ([runningArray count] > 0) {
            return;
        }
        [[NSWorkspace sharedWorkspace] launchApplication:appPath];
    }
    

    相关文章

      网友评论

        本文标题:Mac开发-app开机启动

        本文链接:https://www.haomeiwen.com/subject/vodaqxtx.html