How to wait NSTask to finish in async block

ぐ巨炮叔叔 提交于 2021-01-27 11:57:02

问题


 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
        {
        }

I use dataTaskWithRequest to send async http request and in the completion block, i want to run a 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];

the python task may take a long time so i should wait for its completion. But the NSTaskDidTerminateNotification will not be sent since the NSTask is running in a separate thread. Anyone know how to wait for NSTask to finish in this condition?


回答1:


NSTask has a property 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];


来源:https://stackoverflow.com/questions/36906366/how-to-wait-nstask-to-finish-in-async-block

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