如何等待 NSTask 在异步块中完成

How to wait NSTask to finish in async block

 NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error)
        {
            NSLog(@"Did fail with error %@" , [error localizedDescription]);
            fail();
            return ;
        }
        else
        {
        }

我使用 dataTaskWithRequest 发送异步 http 请求,在完成块中,我想 运行 一个 python script.

 NSTask * task = [[NSTask alloc] init];
    [task setLaunchPath:kPythonPath];
    [task setArguments:@[self.scriptFileFullPath,outputFile]];
    [task launch];
    [task waitUntilExit];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkPythonTaskStatus:) name:NSTaskDidTerminateNotification object:task];

python 任务可能需要很长时间,所以我应该等待它完成。但是 NSTaskDidTerminateNotification 不会被发送,因为 NSTask 在一个单独的线程中 运行ning。有人知道如何等待 NSTask 在这种情况下完成吗?

NSTask 有一个 属性 terminationHandler

The completion block is invoked when the task has completed. The task object is passed to the block to allow access to the task parameters, for example to determine if the task completed successfully.


NSTask * task = [[NSTask alloc] init];
task.launchPath = kPythonPath;
task.arguments = @[self.scriptFileFullPath, outputFile];
task.terminationHandler = ^(NSTask *task){
 // do things after completion
};
[task launch];