How do you wait for an application to close in OS X?

丶灬走出姿态 提交于 2021-01-28 02:02:07

问题


I am using the code below to check if an application is running and close it. Can someone provide an example of how to request an application calose and wait for it to close before proceeding?

+ (BOOL)isApplicationRunningWithName:(NSString *)applicationName {
    BOOL isAppActive = NO;
    NSDictionary *aDictionary;
    NSArray *selectedApps = [[NSWorkspace sharedWorkspace] runningApplications];

    for (aDictionary in selectedApps) {
        if ([[aDictionary valueForKey:@"NSApplicationName"] isEqualToString: applicationName]) {
            isAppActive = YES;
            break;
        }
    }
    return isAppActive;
}

+ (void)stopApplication:(NSString *)pathToApplication {
    NSString *appPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:pathToApplication];
    NSString *identifier = [[NSBundle bundleWithPath:appPath] bundleIdentifier];
    NSArray *selectedApps = [NSRunningApplication runningApplicationsWithBundleIdentifier:identifier];
    // quit all
    [selectedApps makeObjectsPerformSelector:@selector(terminate)];
}

回答1:


You can use Key-Value Observing to observe the terminated property of each running application. This way, you'll get notified when each application terminates, without having to poll.




回答2:


One way would be to periodically call isApplicationRunningWithName on a timer, and wait until that function returns NO.




回答3:


The commandline timelimit will let you send a close signal to an app, wait x seconds, then kill it (or send any other signal you like, kill is -9) if hasn't obeyed the "warning" signal.

(Note: I haven't tried compiling it on Mac, but I believe it's fairly POSIX-compliant code and not Linux-specific as it runs on BSD and others.)



来源:https://stackoverflow.com/questions/9967272/how-do-you-wait-for-an-application-to-close-in-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!