问题
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