有人可以展示一个关于如何结合使用 NSTask 和 NSPipe 来执行此操作的快速示例:
Charlie AI——通过终端运行与AI沟通
我想使用 xcode 和 Objective C 为其创建一个漂亮的 GUI。我想要 2 个 NSTextFields 用于查理的响应和用户输入。然后使用发送按钮将用户输入发送到命令行,然后获取查理的响应并将其发布到 NSTextField 中。
我可以处理 GUI 的东西(NSTextField 等),但我需要 Objective-C 编码部分的帮助。
Thanks!
Elijah
苹果有一些很好的示例代码,展示了如何完成大部分工作。
- https://developer.apple.com/library/archive/samplecode/Moriarity/Introduction/Intro.html https://developer.apple.com/library/archive/samplecode/Moriarity/Introduction/Intro.html
TaskWrapper.m
包含所有聪明的东西,但由于您希望能够将数据发送到任务,因此您需要稍微扩展它,如下所示:
[task setStandardInput: [NSPipe pipe]];
要将输入发送到任务,您可以执行以下操作:
[[[task standardInput] fileHandleForWriting] writeData: ...];
要将 NSTextField 的值转换为数据,您可以执行以下操作:
NSData *data = [[inputTextField stringValue]
dataUsingEncoding:NSUTF8StringEncoding];
...并设置子任务的当前工作目录,请使用[NSTask setCurrentDirectoryPath:] https://developer.apple.com/documentation/foundation/nstask/1413110-currentdirectorypath
e.g.
[task setCurrentDirectoryPath: @"/blah/blah"];
[task setLaunchPath: @"/blah/blah/server.sh"];
.... (other setup code)
[task launch];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)